1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
| package com.example.pj007_imageswitcher;
import java.lang.ref.WeakReference; import java.util.Timer; import java.util.TimerTask;
import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.Button; import android.widget.ImageSwitcher;
public class MainActivity extends Activity {
private static final int IMAGE_SWITCH = 1234;
Button btnNext; Button btnStop; ImageSwitcher imageSwitcher1;
Handler handler;
static class MyHandler extends Handler { WeakReference<MainActivity> mActivity;
MyHandler(MainActivity activity) { mActivity = new WeakReference<MainActivity>(activity); }
@Override public void handleMessage(Message msg) { MainActivity theActivity = mActivity.get(); switch (msg.what) { case IMAGE_SWITCH: theActivity.imageSwitcher1.showNext(); break; default:
} } }
Timer timer;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
handler = new MyHandler(this);
btnNext = (Button) findViewById(R.id.btnNext); btnStop = (Button) findViewById(R.id.btnStop); imageSwitcher1 = (ImageSwitcher) findViewById(R.id.imageSwitcher1);
btnNext.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) { if (timer != null) { timer.cancel(); }
timer = new Timer(true);
timer.schedule(new TimerTask() {
@Override public void run() { handler.sendEmptyMessage(IMAGE_SWITCH); } }, 0, 200); } });
btnStop.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) { if (timer != null) { timer.cancel(); } } }); } }
|