你的位置:首页 > 操作系统

[操作系统]使用Handler和Timer+Timertask实现简单的图片轮播


  布局文件就只放了一个简单的ImageView,就不展示了。

  下面是Activity

 1 package com.example.administrator.handlerthreadmessagedemo; 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 import java.util.Timer;10 11 12 public class MainActivity extends Activity {13 14   private int images[] = new int[]{R.drawable.image1,R.drawable.image2,R.drawable.image3}; //存放图片15 16   private ImageView imageView;17   private int index = 0;  //计算18   private TextView textView;19   private Timer timer = new Timer();20   private Timertask timertask;21 22 23 24   @Override25   protected void onCreate(Bundle savedInstanceState) {26 27     super.onCreate(savedInstanceState);28     setContentView(R.layout.activity_main);29     imageView = (ImageView) findViewById(R.id.imageView);30     textView = (TextView) findViewById(R.id.title);31     timertask = new Timertask();  //放回到Timer中32     timer.schedule(timertask,0,1000); //使用Timer 每隔1秒发送一次空消息33   }34 35   private Handler mhandler = new Handler(){36     @Override37     public void handleMessage(Message msg) {38       super.handleMessage(msg);39       if(msg.what == 0x111){40         index++;41         imageView.setBackgroundResource(images[index % 3]);42       }43     }44   };45 46   class Timertask extends java.util.TimerTask{47 48     @Override49     public void run() {50       mhandler.sendEmptyMessage(0x111);51     }52   }53 54 }