你未必知道:onCreate 中直接线程更新 UI 是不会报错的

在非UI线程中更新UI是会报错的,这是常识,什么叫更新UI呢?举个简单的例子,你调用了一个TextView的 setText()方法就算是更新UI了。

但是下面的代码执行后发现 虽然我在Thread中直接更新了UI,但是没有任何错误出现:

package com.example.threadtest;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
    private TextView text;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        text = (TextView) this.findViewById(R.id.text);
        new Thread(new Runnable() {
            @Override
            public void run() {
                text.setText("dds");
            }
        }).start();
    }
    public void onClick(View view){   
    }  
}

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="${packageName}.${activityClass}" >
    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onClick"
        android:text="不在oncreate中" />   
</RelativeLayout>

这是因为onCreate中时,检查机制还没起作用,因此这个时候是不会报错滴~,当然这样是否是利用了检查机制的漏洞呢?这就有待思考了。

为了验证是不是onCreate中才特有这样的问题,我们将thread放到onclick中:

package com.example.threadtest;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
    private TextView text;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        text = (TextView) this.findViewById(R.id.text);
    }
    public void onClick(View view){   
        new Thread(new Runnable() {
            @Override
            public void run() {
                text.setText("dds");
            }
        }).start();   
    }  
}

当点击button,直接就报错了。

虽然onCreate中一个线程可以直接更新UI,但是显然我们不提倡这样做。