美文网首页简友广场Android开发经验谈
Android 用 AlertDialog 实现页面等待提示

Android 用 AlertDialog 实现页面等待提示

作者: 枫未晚 | 来源:发表于2022-03-26 08:08 被阅读0次

后台的接口返回时间如果比较长,这个时候如果不加任何的提示,会导致用户因为没有看到是否执行而导致重复的操作,为了增加用户的体验感,则需要增加一个等待提示,一般都是展示一个不断旋转的小圆圈

AlertDialog(官方文档)用于提示用户和进行简单交互,可以提供最多三个按钮,标题(title)和提示信息(message)可以通过方法直接设置,如果需要呈现复杂布局,也可以自定义布局并设置

自定义AlertDialog布局实现页面等待提示

这里我使用的是自定义布局来实现不断旋转的小圆圈效果,以下是 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>

小圆圈页面等待提示具体实现代码如下,其中ActivityManager.getCurrentActivity()(相关代码) 是获取了当前正在显示的 Activity,使得不需要在方法中传递 Context 参数也能创建 AlertDialog

object DialogManager {

    fun showRound(): AlertDialog? = ActivityManager.getCurrentActivity()?.let {
        AlertDialog.Builder(it).create().apply {
            window?.run {
                // 设置背景透明,去四个角
                setLayout(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
                )
                // 设置固定宽带,高度自适应
                setBackgroundDrawableResource(R.color.color_transparent)
            }
            // 设置点击dialog的外部能否取消弹窗
            setCanceledOnTouchOutside(false)
            // 设置能不能返回键取消弹窗
            setCancelable(false)
            show()
            setContentView(
                View.inflate(it, R.layout.alert_dialog_round, null).apply {
                    // 设置成顶层视图
                    bringToFront()
                }
            )
        }
    }
}

页面等待提示就完成了,以下是具体使用方式:

val showRound = DialogManager.showRound()
try {
    // 相关操作
} catch (e: Exception) {
    e.printStackTrace()
} finally {
    if (showRound!!.isShowing) {
        showRound.cancel()
    }
}
效果展示

相关文章

网友评论

    本文标题:Android 用 AlertDialog 实现页面等待提示

    本文链接:https://www.haomeiwen.com/subject/ihxdjrtx.html