码迷,mamicode.com
首页 > 其他好文 > 详细

Handler发送Message

时间:2015-08-21 01:48:52      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:

 

    用Handler更新UI

 1 package activity.cyq.handlermessage;
 2 
 3 import android.content.res.Resources;
 4 import android.graphics.Bitmap;
 5 import android.graphics.BitmapFactory;
 6 import android.os.Handler;
 7 import android.os.Message;
 8 import android.support.v7.app.AppCompatActivity;
 9 import android.os.Bundle;
10 import android.widget.Button;
11 import android.widget.ImageView;
12 import android.widget.TextView;
13 import android.widget.Toast;
14 
15 
16 public class MainActivity extends AppCompatActivity {
17     private TextView textView;
18     private Button button;
19     private ImageView imageView;
20 
21     private int[] iamgeId = new int[]{R.drawable.aaa1, R.drawable.aaa3, R.drawable.image1};
22 
23 
24     private Handler handler = new Handler(new Handler.Callback() {
25         @Override
26         public boolean handleMessage(Message msg) {
27             Toast.makeText(MainActivity.this, "这是Handler的回掉函数", Toast.LENGTH_SHORT).show();
28             /*如果返回true则终止handler()的执行 ,可用于对message内容进行判断,今儿决定是否继续对messsage的处理*/
29             return false;
30         }
31     }) {
32         @Override
33         public void handleMessage(Message msg) {
34             super.handleMessage(msg);
35             textView.setText(msg.arg1 + "" + msg.arg2);
36             imageView.setImageBitmap((Bitmap) msg.obj);
37         }
38     };
39 
40     @Override
41     protected void onCreate(Bundle savedInstanceState) {
42         super.onCreate(savedInstanceState);
43         setContentView(R.layout.activity_main);
44 
45         textView = (TextView) findViewById(R.id.textView);
46         button = (Button) findViewById(R.id.button);
47         imageView = (ImageView) findViewById(R.id.imageView);
48         /*通过handler.post(Runnable)方法根性UI*/
49         new Thread() {
50             @Override
51             public void run() {
52                 super.run();
53                 /*创建一个Bitmap对象*/
54                 Resources res = getResources();
55                 Bitmap bmp = BitmapFactory.decodeResource(res, R.drawable.aaa1);
56                 /*发送Message*/
57                 Message message = new Message();
58                 message.arg1 = 123;
59                 message.arg2 = 245;
60                 message.obj = bmp;
61                 /* arg1 arg2 是int类型数据 obj为object类型数据 */
62                 handler.sendMessage(message);
63             }
64         }.start();
65 
66 
67     }
68 
69 
70 }

 

Handler发送Message

标签:

原文地址:http://www.cnblogs.com/chenyangqi/p/4746604.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!