看到標題,你可能會以爲我想寫的,ViewRoot沒建立的時候能夠直接更新嘛.android
然而並非.哈哈bash
測試的android版本: 原生模擬器 9.0app
能夠看到,checkthread()在viewroot的如下地方調用.ide
在看一份代碼:佈局
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tv_content"
android:background="#0ff"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="123123" />
</android.support.constraint.ConstraintLayout>
複製代碼
@Override
protected void onResume() {
super.onResume();
new Thread() {
@Override
public void run() {
super.run();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
TextView view = findView(R.id.tv_content);
view.setText("我在子線程更新");
view.setBackgroundColor(Color.RED);
}
}.start();
}
複製代碼
感興趣的大能夠把上面的代碼跑一下.也不復雜測試
在onResume
這個週期的時候,還延時3秒.viewroot確定建立了,爲何還能更新UI不報錯呢?spa
@Override
protected void onResume() {
super.onResume();
new Thread() {
@Override
public void run() {
super.run();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
TextView view = findView(R.id.tv_content);
view.setText("我在子線程更新");
view.setBackgroundColor(Color.RED);
view.requestLayout();
}
}.start();
}
複製代碼
在最後加一行 view.requestLayout();線程
再試一下,就崩了.code
@Override
protected void onResume() {
super.onResume();
new Thread() {
@Override
public void run() {
super.run();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
TextView view = findView(R.id.tv_content);
view.setText("我在子線程更新");
view.setBackgroundColor(Color.RED);
view.invalidate();
}
}.start();
}
複製代碼
view.requestLayout()
改爲view.invalidate();
cdn
不會崩.
實際上,就是隻要你改view,不觸發checkThread()
就沒事
而TextView的寬高不改變,也不會去觸發requestLayout()
, 修改背景也一樣.不會觸發view的位置大小改變.
固然.這種狀況.不是每一個版本的android都有用. 仍是要規範的去主線程更新UI.哈哈
Flutter:782978118
Android:493180098