zoukankan      html  css  js  c++  java
  • Handler机制来处理子线程去更新UI线程控件

    public class HandlerTestActivity extends Activity {
        private TextView tv;
        private static final int UPDATE = 0;
        private Handler handler = new Handler() {
    
            @Override
            public void handleMessage(Message msg) {
                // TODO 接收消息并且去更新UI线程上的控件内容
                if (msg.what == UPDATE) {
                    // Bundle b = msg.getData();
                    // tv.setText(b.getString("num"));
                    tv.setText(String.valueOf(msg.obj));
                }
                super.handleMessage(msg);
            }
        };
    
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            tv = (TextView) findViewById(R.id.tv);
    
            new Thread() {
                @Override
                public void run() {
                    // TODO 子线程中通过handler发送消息给handler接收,
                //由handler去更新TextView的值
                    try {
                        for (int i = 0; i < 100; i++) {
                            Thread.sleep(500);
                            Message msg = new Message();
                            msg.what = UPDATE;
                            // Bundle b = new Bundle();
                            // b.putString("num", "更新后的值:" + i);
                            // msg.setData(b);
                            msg.obj = "更新后的值:" + i;
                            handler.sendMessage(msg);
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        }
    
    }                
  • 相关阅读:
    HttpRunner3.X
    基于C++的ByteBuf封装
    关于matlab的配色
    关于样本方差的无偏估计
    使用Python求解Nonogram
    菜鸡的一些力扣记录
    LeetCode链表练习
    C语言中的链表
    Python中的链表简介
    Nebula Graph 源码解读系列 | Vol.03 Planner 的实现
  • 原文地址:https://www.cnblogs.com/kingsam/p/5584590.html
Copyright © 2011-2022 走看看