后臺(tái)的接口返回時(shí)間如果比較長,這個(gè)時(shí)候如果不加任何的提示,會(huì)導(dǎo)致用戶因?yàn)闆]有看到是否執(zhí)行而導(dǎo)致重復(fù)的操作,為了增加用戶的體驗(yàn)感,則需要增加一個(gè)等待提示,一般都是展示一個(gè)不斷旋轉(zhuǎn)的小圓圈
AlertDialog(官方文檔)用于提示用戶和進(jìn)行簡單交互,可以提供最多三個(gè)按鈕,標(biāo)題(title)和提示信息(message)可以通過方法直接設(shè)置,如果需要呈現(xiàn)復(fù)雜布局,也可以自定義布局并設(shè)置
自定義AlertDialog布局實(shí)現(xiàn)頁面等待提示
這里我使用的是自定義布局來實(shí)現(xiàn)不斷旋轉(zhuǎn)的小圓圈效果,以下是 xml 布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center">
<ProgressBar
style="@android:style/Widget.ProgressBar.Inverse"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
在res/values/colors.xml
文件中增加將要用到的背景色:
<color name="color_transparent">#00000000</color>
小圓圈頁面等待提示具體實(shí)現(xiàn)代碼如下,其中ActivityManager.getCurrentActivity()
(相關(guān)代碼) 是獲取了當(dāng)前正在顯示的 Activity,使得不需要在方法中傳遞 Context 參數(shù)也能創(chuàng)建 AlertDialog
object DialogManager {
fun showRound(): AlertDialog? = ActivityManager.getCurrentActivity()?.let {
AlertDialog.Builder(it).create().apply {
window?.run {
// 設(shè)置背景透明,去四個(gè)角
setLayout(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
)
// 設(shè)置固定寬帶,高度自適應(yīng)
setBackgroundDrawableResource(R.color.color_transparent)
}
// 設(shè)置點(diǎn)擊dialog的外部能否取消彈窗
setCanceledOnTouchOutside(false)
// 設(shè)置能不能返回鍵取消彈窗
setCancelable(false)
show()
setContentView(
View.inflate(it, R.layout.alert_dialog_round, null).apply {
// 設(shè)置成頂層視圖
bringToFront()
}
)
}
}
}
頁面等待提示就完成了,以下是具體使用方式:
val showRound = DialogManager.showRound()
try {
// 相關(guān)操作
} catch (e: Exception) {
e.printStackTrace()
} finally {
if (showRound!!.isShowing) {
showRound.cancel()
}
}
效果展示