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...");
                }
            }
        }
    
    }
  • 相关阅读:
    break和continue
    while循环嵌套
    while循环语句
    SDUT 2766-小明传奇2(母函数)
    那些奇妙的"大师"是怎样炼成的(科学、迷信、心理)
    深入理解Linux字符设备驱动
    [从头学数学] 第162节 锐角三角函数
    iOS将数组中的内容分拼接成字符串
    win10 UWP 全屏
    杂(三)-The type java.lang.Object cannot be resolved It is indirectly referenced ...
  • 原文地址:https://www.cnblogs.com/zhujiabin/p/4258852.html
Copyright © 2011-2022 走看看