1 | public class MainActivity extends Activity { //定義切換的圖片的數組id int imgids[] = new int[]{ R.drawable.s_1, R.drawable.s_2,R.drawable.s_3, R.drawable.s_4,R.drawable.s_5,R.drawable.s_6, R.drawable.s_7,R.drawable.s_8 }; int imgstart = 0; final Handler myHandler = new Handler() { @Override //重寫handleMessage方法,根據msg中what的值判斷是否執行後續操作 public void handleMessage(Message msg) { if(msg.what == 0x123) { imgchange.setImageResource(imgids[imgstart++ % 8]); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final ImageView imgchange = (ImageView) findViewById(R.id.imgchange); //使用定時器,每隔200毫秒讓handler發送一個空信息 new Timer().schedule(new TimerTask() { @Override public void run() { myHandler.sendEmptyMessage(0x123); } }, 0,200); } } |