您的位置:首页 > 产品设计 > UI/UE

Android中关于“UI只能在主线程中更新”说法的理解

2018-01-29 16:43 369 查看
首先该说法不严谨,正确的说法是,UI只能在创建它的线程中更新。如下代码说明这个问题

1、MainActivity

package cn.test.uitest;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

public void changeText(View view) {
new Thread(new Runnable() {
@Override
public void run() {
TextView textView = new TextView(MainActivity.this);
textView.setText("修改后的文字");
Log.d("changeText" , textView.getText().toString());
}
}).start();
}
}

2、activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
tools:context="cn.test.uitest.MainActivity">

<Button
android:text="改变文字"
android:onClick="changeText"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

</LinearLayout>

功能很简单,在按钮的点击事件中新建一个子线程,在该线程中创建一个TextView的UI并对其进行赋值,然后获取值并打印。点击按钮后,控制台的日志如下

01-29 16:31:46.871 3163-3185/cn.test.uitest D/changeText: 修改后的文字
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息