package com.example.testandroid;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends Activity {
// 声明Handler对象
private Handler handler;
// 切换显示图片数组id的下标
private int index;
// 切换是否进行
private boolean isRun = true;
public static final int CHANGE_IMAGE = 1;
// 切换的图片id数组
private int[] images = new int[] { R.drawable.drops_icon,
R.drawable.drops_icon_selected};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == CHANGE_IMAGE) {
ImageView imageView = (ImageView) findViewById(R.id.image);
// 动态改变ImageView里面的图片
imageView.setImageResource(images[msg.getData().getInt(
"index")]);
}
}
};
// 获得按钮
Button btn1 = (Button) findViewById(R.id.btn1);
Button btn2 = (Button) findViewById(R.id.btn2);
btn2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
isRun = false;
}
});
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
isRun = true;
new Thread() {
public void run() {
for (index = 0; isRun; index++) {
Message msg = new Message();
msg.what = CHANGE_IMAGE;
// 创建Bundle对象,封装数据
Bundle bundle = new Bundle();
bundle.putInt("index", index);
msg.setData(bundle);
// 发送消息
handler.sendMessage(msg);
// 循环切换
if (index >=1) {
index = -1;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
});
}
}