Android 记子线程更新UI不崩的一个现象 前言 checkthread 把上面的代码改一下 再来 总结

前言

看到标题,你可能会觉得我想写的,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

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