文章目录
- 下面启动了一个子线程,因为子线程无法直接对UI进行操作,只能够通过Handler,发送消息给主线程,也就是UI线程,然后UI线程对UI进行操作,这样是为了线程安全做考虑。
public class MainActivity extends AppCompatActivity {
private ImageView show;
static class MyHandler extends Handler {
private WeakReference<MainActivity> activity;
public MyHandler(WeakReference<MainActivity> activity) {
this.activity = activity;
}
private int[] imageIds = new int[]{R.drawable.ic_android_black_24dp,
R.drawable.ic_launcher_background};
private int currentImageId = 0;
@Override
public void handleMessage(@NonNull Message msg) {
if (msg.what == 0x1233) {
activity.get().show.setImageResource(imageIds[currentImageId++ % imageIds.length]);
}
}
}
MyHandler myHandler = new MyHandler(new WeakReference(this));
@SuppressLint("ClickableViewAccessibility")
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
show = findViewById(R.id.show);
new Timer().schedule(new TimerTask() {
@Override
public void run() {
myHandler.sendEmptyMessage(0x1233);
}
}, 0, 1200);
}
}