Android子线程更新UI的方法总结
消息机制,对于Android开发者来说,应该是非常熟悉。对于处理有着大量交互的场景,采用消息机制,是再好不过了。有些特殊的场景,比如我们都知道,在Android开发中,子线程不能更新UI,而主线程又不能进行耗时操作,一种常用的处理方法就是,在子线程中进行耗时操作,完成之后发送消息,通知主线程更新UI。或者使用异步任务,异步任务的实质也是对消息机制的封装。
关于子线程到底能不能更新UI这个问题,之前看到一篇文章很有趣,让我对这个问题也有了新的认识,那么我也来写个简单例子测试下,布局文件如下:
复制代码
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="com.example.joy.messagetest.MainActivity">
android:id="@+id/tv_test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="HelloWorld!"/>
复制代码
布局中只有一个TextView,java代码如下:
复制代码
packagecom.example.joy.messagetest;
importandroid.support.v7.app.AppCompatActivity;
importandroid.os.Bundle;
importandroid.view.View;
importandroid.widget.TextView;
publicclassMainActivityextendsAppCompatActivity{
privateTextViewmTvTest;
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
newThread(newRunnable(){
@Override
publicvoidrun(){
mTvTest.setText("子线程可以更新UI");
}
}).start();
}
privatevoidinitView(){
mTvTest=(TextView)findViewById(R.id.tv_test);
}
}
复制代码
代码也很简单,我开启子线程,在子线程中,将TextView内容设置为“子线程可以更新UI”,而在布局文件中,TextView的text为“Helloworld!”,那么现在运行程序,可能会出现的结果有三种:
程序崩了,抛异常了:说明子线程不能更新UI
程序正常运行,textview上面显示“HelloWorld!”:说明子线程不能更新UI
程序正常运行,textview上面显示“子线程可以更新UI”:说明子线程可以更新UI
运行程序,结果如下:
这说明什么?从结果看,子线程更新UI成功了。真的是这样吗?我自己也不相信,赶紧再验证一遍。这次我在布局文件中添加一个Button,修改后的布局文件如下:
复制代码
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="com.example.joy.messagetest.MainActivity">
android:id="@+id/tv_test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="HelloWorld!"/>
|
|