zoukankan      html  css  js  c++  java
  • Android Handler传递参数动态更新UI界面demo

    package com.example.demo_test;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Message;
    import android.view.Menu;
    import android.widget.TextView;
    
    public class MainActivity extends Activity {
        private TextView tvShow;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            tvShow = (TextView) findViewById(R.id.tv_show);
            new Thread(new ThreadChangeUI(handler)).start();
        }
    
        // handler类接收数据
        Handler handler = new Handler() {
            public void handleMessage(Message msg) {
                if (msg.what == 1) {
                    // 动态更新UI界面
                    String str = msg.getData().getInt("num") + "";
                    System.out.println("str----------------->" + str);
                    tvShow.setText(str);
                }
            };
        };
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            getMenuInflater().inflate(R.menu.activity_main, menu);
            return true;
        }
    
    }

    线程:

    package com.example.demo_test;
    
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Message;
    
    public class ThreadChangeUI implements Runnable {
        private Handler handler;
        private int num = 0;
    
        public ThreadChangeUI(Handler handler) {
            // TODO Auto-generated constructor stub
            this.handler = handler;
        }
    
        @Override
        public void run() {
            // 每秒改变textview的值
            while (true) {
                try {
                    Thread.sleep(1000);
                    Message msg = new Message();
                    msg.what = 1;
                    // handler传递参数
                    // handler.sendMessage(msg);
                    Bundle bundle = new Bundle();
                    bundle.putInt("num", num++);
                    System.out.println("num---------->" + num);
                    msg.setData(bundle);
                    handler.sendMessage(msg);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    System.out.println("thread error...");
                }
            }
        }
    
    }
  • 相关阅读:
    elasticsearch-排序(六)
    elasticsearch-分词器(五)
    elasticsearch-搜索-基本搜索(四)
    elasticsearch-文档(三)
    elasticsearch-集群(二)
    FFmpeg架构之I/O模块分析
    DirectShow 在 VS2010 中开发环境的设置
    预编译头文件来自编译器的早期版本,或者预编译头为 C++ 而在 C 中使用它(或相反)
    2012年软件开发者薪资调查报告
    深入了解 VP8
  • 原文地址:https://www.cnblogs.com/zhujiabin/p/4258852.html
Copyright © 2011-2022 走看看