Android之在子线程更新UI实践
简言:首先和其他许多的GUI库一样,Android的UI线程是不安全的。则如果想更新UI就必须在主线程中进行,否则就会出现异常。
我们通过一个小Demo来检验一下
acttvity-main.xml代码如下:
<?xml version="1.0" encoding="utf-8"?>
<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="com.johnnyzhou.androidthreadtest.MainActivity">
<Button
android:id="@+id/btn_change"
android:layout_centerHorizontal="true"
android:text="点击改变文字"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/text"
android:layout_centerInParent="true"
android:textSize="20sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"/>
</RelativeLayout>
代码如上所示,布局文件中定义了两个空间,一个Button按钮,一个显示Helloworld的TextView,现在我们要实现点击Button
按钮改变TextView的文本值为Hello JohnnyZhou.
接下来修改MainActivity的代码:
package com.johnnyzhou.androidthreadtest;
import android.support.v7.app.Ap