Android 記子線程更新UI不崩的一個現象

前言

看到標題,你可能會覺得我想寫的,ViewRoot沒創建的時候可以直接更新嘛.

然而並不是.哈哈

checkthread

可以看到,checkthread()在viewroot的以下地方調用.

在看一份代碼:

佈局

<?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不報錯呢?

把上面的代碼改一下

 @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();

再試一下,就崩了.

再來

@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();

不會崩.


總結

實際上,就是隻要你改view,不觸發checkThread()就沒事

而TextView的寬高不改變,也不會去觸發requestLayout(),
修改背景也同樣.不會觸發view的位置大小改變.

當然.這種情況.不是每個版本的android都有用.
還是要規範的去主線程更新UI.哈哈


期待你的留言 點贊

交流羣:

Flutter:782978118

Android:493180098

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章