我们要将一个张图片显示在屏幕上,首先需要创建一个显示图片的对象,在Android

中,这个对象是ImageView对象,然后通过setImageResources 方法来设置要显示的图片资源索引。当然,还可以对图片执行一些其它的操作,比如设置它的Alpha值等。这里通过一个示例来给大家演示,我们另起一个线程来改变图片的Alpha值。


 



 


Activity01类 

Java代码
1. package xiaohang.zhimeng;
2.
3. import android.app.Activity;
4. import android.os.Bundle;
5. import android.os.Handler;
6. import android.os.Message;
7. import android.widget.ImageView;
8. import android.widget.TextView;
9.
10. public class Activity01 extends Activity {
11. // 声明ImageView对象
12. ImageView imageView;
13. // 声明TextView
14. TextView textView;
15. // ImageView的alpha值
16. int image_alpha = 255;
17. // Handler对象用来给UI_Thread的MessageQueue发送消息
18. Handler mHandler;
19. // 线程是否运行判断变量
20. boolean isrung = false;
21.
22. @Override
23. public void onCreate(Bundle savedInstanceState) {
24. super.onCreate(savedInstanceState);
25. setContentView(R.layout.main);
26. isrung = true;
27. // 获得ImageView的对象
28. imageView = (ImageView) this.findViewById(R.id.ImageView01);
29. textView = (TextView) this.findViewById(R.id.TextView01);
30. // 设置imageView的图片资源。同样可以再xml布局中像下面这样写
31. // android:src="@drawable/logo"
32. imageView.setImageResource(R.drawable.logo);
33. // 设置imageView的Alpha值
34. imageView.setAlpha(image_alpha);
35. // 开启一个线程来让Alpha值递减
36. new Thread(new Runnable() {
37. @Override
38. public void run() {
39. while (isrung) {
40. try {
41. Thread.sleep(200);
42. // 更新Alpha值
43. updateAlpha();
44. } catch (InterruptedException e) {
45. e.printStackTrace();
46. }
47. }
48. }
49. }).start();
50. // 接受消息之后更新imageview视图
51. mHandler = new Handler() {
52. @Override
53. public void handleMessage(Message msg) {
54. super.handleMessage(msg);
55. imageView.setAlpha(image_alpha);
56. // 设置textview显示当前的Alpha值
57. textView.setText("现在的alpha值是:" + Integer.toString(image_alpha));
58. // 刷新视图
59. imageView.invalidate();
60. }
61. };
62. }
63.
64. // 更新Alpha
65. public void updateAlpha() {
66. if (image_alpha - 7 >= 0) {
67. image_alpha -= 7;
68. } else {
69. image_alpha = 0;
70. isrung = false;
71. }
72. // 发送需要更新imageview视图的消息-->这里是发给主线程
73. mHandler.sendMessage(mHandler.obtainMessage());
74. }
75. }
布局文件main.xml

1. <?xml version="1.0" encoding="utf-8"?>
2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. android:orientation="vertical"
4. android:layout_width="fill_parent"
5. android:layout_height="fill_parent"
6. >
7. <ImageView
8. android:id="@+id/ImageView01"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. />
12. <TextView
13. android:id="@+id/TextView01"
14. android:layout_below="@id/ImageView01"
15. android:layout_width="fill_parent"
16. android:layout_height="wrap_content"
17. android:text="@string/hello"
18. />
19. </LinearLayout>
源码下载。
​​Xh_04_05_Test_01.rar​​