android 简单的相册查看器
1、创建工程:HandlerTest02
2、准备程序中需要的图片资源,将图片资源存放在res/drawable-mdpi目录下
3、编写布局文件main.xml:代码如下:
View Code
4、开发换图的线程。在目录下新建一个MyThread.java文件。代码如下:
View Code
1 package com.handlerTest02;
2
3 public class MyThread extends Thread{
4 HandlerTest02 handlerTestActivity;
5 int what=1;
6 public MyThread( HandlerTest02 handlerTestActivity){
7 this.handlerTestActivity=handlerTestActivity;
8 }
9 @Override
10 public void run() {
11 while(true){
12 //发送消息
13 handlerTestActivity.myHandler.sendEmptyMessage((what++)%7);
14 try{
15 Thread.sleep(2000); //休眠两秒钟
16 }catch(Exception e){
17 e.printStackTrace(); //打印异常消息
18 }
19 }
20 }
21
22 }
5、开发主逻辑代码。代码如下:
View Code
1 package com.handlerTest02;
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
9 public class HandlerTest02 extends Activity {
10 /** Called when the activity is first created. */
11 ImageView myImageView;
12 Handler myHandler=new Handler(){
13 public void handleMessage(Message msg){
14 switch(msg.what){
15 case 0:
16 myImageView.setImageResource(R.drawable.a);
17 break;
18 case 1:
19 myImageView.setImageResource(R.drawable.b);
20 break;
21 case 2:
22 myImageView.setImageResource(R.drawable.c);
23 break;
24 case 3:
25 myImageView.setImageResource(R.drawable.d);
26 break;
27 case 4:
28 myImageView.setImageResource(R.drawable.e);
29 break;
30 case 5:
31 myImageView.setImageResource(R.drawable.f);
32 break;
33 case 6:
34 myImageView.setImageResource(R.drawable.g);
35 break;
36 }
37 super.handleMessage(msg);
38 }
39 };
40
41 @Override
42 public void onCreate(Bundle savedInstanceState) {
43 super.onCreate(savedInstanceState);
44 setContentView(R.layout.main);
45 myImageView=(ImageView)findViewById(R.id.myImageView);
46 MyThread myThread=new MyThread(this);
47 myThread.start();
48 }
49 }
6、运行效果如下:每隔两秒钟自动更换下一张照片。
这只是一个简单的程序,主要是了解Handler消息传递机制的使用。