本文来自:安卓航班网
1、创建工程:HandlerTest02
2、准备程序中需要的图片资源,将图片资源存放在res/drawable-mdpi目录下
3、编写布局文件main.xml:代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
androidrientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<ImageView
android:id="@+id/myImageView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="@drawable/a"
android:layout_gravity="center"
/>
</LinearLayout>
4、开发换图的线程。在目录下新建一个MyThread.java文件。代码如下:
package com.handlerTest02;
public class MyThread extends Thread{
HandlerTest02 handlerTestActivity;
int what=1;
public MyThread( HandlerTest02 handlerTestActivity){
this.handlerTestActivity=handlerTestActivity;
}
@Override
public void run() {
while(true){
//发送消息
handlerTestActivity.myHandler.sendEmptyMessage((what++)%7);
try{
Thread.sleep(2000); //休眠两秒钟
}catch(Exception e){
e.printStackTrace(); //打印异常消息
}
}
}
}
5、开发主逻辑代码。代码如下:
package com.handlerTest02;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;
public class HandlerTest02 extends Activity {
/** Called when the activity is first created. */
ImageView myImageView;
Handler myHandler=new Handler(){
public void handleMessage(Message msg){
switch(msg.what){
case 0:
myImageView.setImageResource(R.drawable.a);
break;
case 1:
myImageView.setImageResource(R.drawable.b);
break;
case 2:
myImageView.setImageResource(R.drawable.c);
break;
case 3:
myImageView.setImageResource(R.drawable.d);
break;
case 4:
myImageView.setImageResource(R.drawable.e);
break;
case 5:
myImageView.setImageResource(R.drawable.f);
break;
case 6:
myImageView.setImageResource(R.drawable.g);
break;
}
super.handleMessage(msg);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myImageView=(ImageView)findViewById(R.id.myImageView);
MyThread myThread=new MyThread(this);
myThread.start();
}
}
6、运行效果如下:每隔两秒钟自动更换下一张照片。
这只是一个简单的程序,主要是了解Handler消息传递机制的使用。
原文地址:http://www.apkway.com/forum.php?mod=viewthread&tid=1788&extra=page%3D2