android 创建子线程来执行耗时操作 友好提示加载中,然后显示UI

比如我们要执行一个耗时的操作,那么可能这样操作:

1、先show一个等待对话框,然后下面加载,成功了,将其关闭。

2、直接将其放在一个fragment的布局中,等待显示一个布局,数据加载成功以后,显示RecyclerView即可。

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:layout_gravity="center"
        android:orientation="horizontal"
        android:id="@+id/ll_loading">
        <com.google.android.material.progressindicator.CircularProgressIndicator
            android:id="@+id/chat_item_progress"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:indeterminate="true"
            android:visibility="visible"
            app:indicatorColor="@array/custom_progress_colors"
            app:indicatorSize="@dimen/space_25" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/load_waiting"/>
    </LinearLayout>
</FrameLayout>

直接上代码:

class threadClass extends Thread {

    @Override
    public void run() {
        super.run();
        try{
            ....
        }catch(Exception ex){
            ...
     }
        handler.sendEmptyMessage(0);
    } 
}

Handler handler = new Handler(Looper.myLooper()) {
    @Override
    public void dispatchMessage(@NonNull Message msg) {
        super.dispatchMessage(msg);
        //更新ui
    }
}

调用:

new threadClass().start();
道法自然
原文地址:https://www.cnblogs.com/jiduoduo/p/15001179.html