Android 使用Handler在线程中对UI元素进行内容更新

关键字: 线程更新UI Handler

 

android应用开发过程中,为保证用户界面的流畅,往往需要在线程中进行Activity中的文本、图片等的内容替换。而由于线程独立于主线程,无法直接访问主线程中的元素,故而无法直接对界面内容进行更新。为此,在android中引入了 Handler机制和Message来通过消息进行线程中UI更新。下面是具体的实现过程(以更新一个TextView中的文字为例):

1. 在主线程OnCreate()方法中,对要更新的TextView进行定义

tvTimer = (TextView) findViewById(R.id.timer);

2. 在主线程中声明一个Handler并对其内容进行实现

    private Handler timerHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				tvTimer.setText(msg.getData().getString("Timer"));
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
    };
3. 在主线程中声明一个继承 Thread 类的内部类,并实现 run() 方法

4. 在run()方法中,生成消息,并将消息发送给步骤2中声明的Handler

    			Message msg = new Message();
    			msg.what = 0;
    			Bundle bundle = new Bundle();
    			bundle.putString("Timer", sdf.format(new Date()));
    			msg.setData(bundle);
    			timerHandler.sendMessage(msg);

5. 在OnCreate()方法中启动线程

 

经过以上步骤,线程即可以发送消息的方式更新UI里的内容。详细的实现代码如下:

 

附: 代码清单

-----------------------------------

MainActivity.java

package com.example.handlertest;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }
    
    private void init() {
    	tvTimer = (TextView) findViewById(R.id.timer);
    	timerThread = new TimerThread();
    	timerThread.start();
    }
	
	private TextView tvTimer;
    private TimerThread timerThread;
    private Handler timerHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				tvTimer.setText(msg.getData().getString("Timer"));
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
    };
    
    class TimerThread extends Thread {
		@Override
    	public void run() {
    		while (true) {
    			SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
    			Message msg = new Message();
    			msg.what = 0;
    			Bundle bundle = new Bundle();
    			bundle.putString("Timer", sdf.format(new Date()));
    			msg.setData(bundle);
    			timerHandler.sendMessage(msg);
    			try {
    				Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
    		}
    	}
    }
}

Activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${relativePackage}.${activityClass}" >

    <TextView
        android:id="@+id/timer"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</RelativeLayout>


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值