android中用线程更新UI,报错only the original thread that created a view hierarchy can touch its views

本文介绍在Android开发中如何正确更新UI,特别是在需要高频率更新UI的场景下,如毫秒级时钟应用。文章通过实例讲解了直接在子线程更新UI导致的问题,并演示了使用Handler机制将更新操作回调到主线程的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

        Android开发中难免要更新UI,比如做一个时钟,时间总要动吧?这时间就要更新UI,但很多时间不方便把更新UI的代码放在主线程中,就比如说做一个精确度到毫秒级的时钟,因为精度是毫秒级的,那么更新时间的频率也要是毫秒级的,不然所谓的毫秒级就没什么意义了。这样一来,就要在很短的时间就更新一次UI,如果放在主线程里做,那么主线程的大部分工作是耗在这了,程序就会很卡,所以一般就会放到一个子线程中去做这些事,这样主线程就不卡了。但是,问题是不能直接在子线程中直接更新UI,先来看一下代码。

        先建一个TextView :

<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
</RelativeLayout>

        然后用它来显示当前时间,精确到毫秒,因为精确到毫秒,所以要频繁地更新UI,因此要开一个线程,不然在主线程里做这么频繁的操作,程序要卡死咯。如果直接在线程里更新UI如下:

public class MainActivity extends Activity {
	TextView tv;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		tv=(TextView)findViewById(R.id.tv);
		MyThread thread=new MyThread();
		thread.start();
	}
	
	class MyThread extends Thread{
		@Override
		public void run() {
			while(true){;
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
				tv.setText(df.format(new Date()));
				try {
					Thread.sleep(10);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
}

        这样会报错,only the original thread that created a view hierarchy can touch its views,不能直接在非主线程里更新,解决方法是用handler,代码如下:

public class MainActivity extends Activity {
	TextView tv;
	Handler handler;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		tv=(TextView)findViewById(R.id.tv);
		handler=new Handler(){
			@Override
			public void handleMessage(Message msg) {
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
				tv.setText(df.format(new Date()));
			}
		};
		MyThread thread=new MyThread();
		thread.start();
	}
	
	class MyThread extends Thread{
		@Override
		public void run() {
			while(true){
				handler.sendEmptyMessage(0);
				try {
					Thread.sleep(10);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值