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...");
                }
            }
        }
    
    }
  • 相关阅读:
    xfire webServeic 例子
    Spring3 url匹配规则
    js 字符串转化成数字
    JS回车事件,兼容目前所有浏览器
    笔记:Zygote和SystemServer进程启动过程
    安卓Task和Back Stack
    札记:Property动画
    札记:翻译-使用Scene和Transition实现【场景切换】动画效果
    算法:排序
    [BOT]自定义ViewPagerStripIndicator
  • 原文地址:https://www.cnblogs.com/zhujiabin/p/4258852.html
Copyright © 2011-2022 走看看