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

Handler用法

时间:2016-08-03 01:30:32      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:

handler :更新UI的机制,消息的处理机制

四种用法sendMessage、sendMessageDelayed、post(runnable)、postDelayed(Runnable,long)

 

post用法

    private android.os.Handler handler = new android.os.Handler();

    new Thread() {
            public void run() {
                try {
                    Thread.sleep(1000);
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            text.setText("123");
                        }
                    });
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();

 

sendMessage用法

    private android.os.Handler handler = new android.os.Handler() {
        @Override
        public void handleMessage(Message msg) {
            text.setText("" + msg.arg1);
        }
    };

   new Thread() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                    Message message = new Message();
                    message.arg1 = 100;
            //handler.sendMessage(XXX);对象可以是int,也可以是obj对象
            //message.obj=Person; Person是一个实体类对象 handler.sendMessage(message); } catch (InterruptedException e) { e.printStackTrace(); } } }.start();

 


handler.postDelayed(task,time);可以作为viewpager的图片自动切换

   private android.os.Handler handler = new android.os.Handler();   
  
   private Myrunnable myrunnable = new Myrunnable(); class Myrunnable implements Runnable { @Override public void run() {
        //做需要循环的操作 handler.postDelayed(myrunnable, 1000); } }
  handler.postDelayed(myrunnable,1000);//调用

 

handler.removeCallbacks(myrunnable);//移除

Handler用法

标签:

原文地址:http://www.cnblogs.com/lyxin/p/5731259.html

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