Handler发送Message

用Handler更新UI

 package activity.cyq.handlermessage;

 import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast; public class MainActivity extends AppCompatActivity {
private TextView textView;
private Button button;
private ImageView imageView; private int[] iamgeId = new int[]{R.drawable.aaa1, R.drawable.aaa3, R.drawable.image1}; private Handler handler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
Toast.makeText(MainActivity.this, "这是Handler的回掉函数", Toast.LENGTH_SHORT).show();
/*如果返回true则终止handler()的执行 ,可用于对message内容进行判断,今儿决定是否继续对messsage的处理*/
return false;
}
}) {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
textView.setText(msg.arg1 + "" + msg.arg2);
imageView.setImageBitmap((Bitmap) msg.obj);
}
}; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); textView = (TextView) findViewById(R.id.textView);
button = (Button) findViewById(R.id.button);
imageView = (ImageView) findViewById(R.id.imageView);
/*通过handler.post(Runnable)方法根性UI*/
new Thread() {
@Override
public void run() {
super.run();
/*创建一个Bitmap对象*/
Resources res = getResources();
Bitmap bmp = BitmapFactory.decodeResource(res, R.drawable.aaa1);
/*发送Message*/
Message message = new Message();
message.arg1 = 123;
message.arg2 = 245;
message.obj = bmp;
/* arg1 arg2 是int类型数据 obj为object类型数据 */
handler.sendMessage(message);
}
}.start(); } }
上一篇:【转】linux expr命令参数及用法详解


下一篇:解决 error: failed to push some refs to *.git