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...");
                }
            }
        }
    
    }
  • 相关阅读:
    AS出现Connection timed out
    关于eclipse出现The selection cannot be launched,and there are no recent launches
    第十周周赛题解
    FJUT 2401 尼克的任务
    关于3月份的学习总结
    人生的第一题图论
    第六周周赛题解
    Drupal8 社区文档之积极的Drupal版本
    Drupal8 社区文档之Drupal安全吗
    Drupal8 社区文档之技术堆栈
  • 原文地址:https://www.cnblogs.com/zhujiabin/p/4258852.html
Copyright © 2011-2022 走看看