最终使用代码如下
GlobalScope.progress(context,{
//这里写后台请求代码比如
val users = RetrofitServiceManager.create(PosApi::class.java).searchUser(user).get()
}){
//请求完后的操作
adapter.notifyDataSetChanged()
}
第一步构建一个进度条提示的Dialog
1.布局文件如下
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:background="@drawable/group_box_progress"
android:padding="@dimen/padding_m">
<androidx.core.widget.ContentLoadingProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/loadingImageView"
style="?android:attr/progressBarStyleSmall"/>
<TextView
android:id="@+id/id_tv_loadingmsg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="@dimen/padding_s"
android:layout_marginRight="@dimen/padding_m"
android:textColor="@color/colorContent"
android:textSize="15dp" />
</LinearLayout>
2.代码如下
class CustomProgressDialog(context: Context,theme: Int,strMessage: String) : Dialog(context, theme) {
constructor(context: Context, strMessage: String) : this(context,
R.style.CustomProgressDialog,strMessage)
fun setMessage(message: String) {
id_tv_loadingmsg.text = message
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
if (!hasFocus) {
dismiss()
}
}
init {
this.setContentView(R.layout.customprogressdialog)
this.window?.attributes?.gravity = Gravity.CENTER
this.window?.attributes?.dimAmount = 0.1f
id_tv_loadingmsg.text = strMessage
setCanceledOnTouchOutside(false)
loadingImageView.indeterminateDrawable.setColorFilter(ContextCompat.getColor(context, R.color.colorBlue),PorterDuff.Mode.MULTIPLY )
}
}
3.样式也给上
<style name="CustomProgressDialog" parent="@style/CustomDialog">
<item name="android:windowBackground">@drawable/group_box_progress</item>
<item name="android:windowNoTitle">true</item>
</style>
//group_box_progress文件
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="#5A5959" />
<corners android:radius="5dp"/>
<stroke android:color="@color/colorContentDark" android:width="0.1dp" />
</shape>
第二步构建协程
fun GlobalScope.progress(context: Context, back: (() -> Unit)?, main: (() -> Unit)?){
val progressDialog = CustomProgressDialog(context,"正常请求数据,请稍后......")
progressDialog.show()
launch(Dispatchers.IO){
try {
back?.invoke()
}catch (e: Exception){
e.printStackTrace()
}
withContext(Dispatchers.Main){
progressDialog.dismiss()
main?.invoke()
}
}
}