package com.example.handledemos;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
/**
* Handler的用法
* 1、Handler用于发送和处理消息。
* 2、在多线程中更新ui。
* @author lzl
*传入的callback类用于拦截handler发送的消息。
*/
public class MainActivity extends Activity implements OnClickListener {
private TextView textView;
private ImageView imageView;
private Button button;
int images[] = {R.drawable.iamge1,R.drawable.image2,R.drawable.image3};
private int index;
private MyRunnerble myrunnerble = new MyRunnerble(); //这里是创建对象
private Handler handler = new Handler(new Callback() { //callback类 用于拦截发送的信息。
@Override
public boolean handleMessage(Message msg) {
if(msg.arg1 == 10){
Toast.makeText(getApplicationContext(), "---"+msg.arg1, Toast.LENGTH_SHORT).show();
handler.removeCallbacks(myrunnerble);
return true;
}
return false;
}
}){
public void handleMessage(Message msg) {
Toast.makeText(getApplicationContext(), "***"+msg.arg1, Toast.LENGTH_SHORT).show();
}
};
class MyRunnerble implements Runnable{
@Override
public void run() {
index++;
index = index % 3;
handler.postDelayed(myrunnerble, 1000); //在线程中执行,延迟时间1秒。
imageView.setImageResource(images[index]);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView1);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(this);
handler.postDelayed(myrunnerble, 1000);
}
@Override
public void onClick(View view) {
// handler.removeCallbacks(myrunnerble); //通过点击事件使图片停止切换。
Message message = new Message();
message.arg1 = 10;
handler.sendMessage(message);
}
}