构建并显示弹出式消息

尝试使用 Compose 方式
Jetpack Compose 是推荐用于 Android 的界面工具包。了解如何在 Compose 中添加通知。

您可以使用 Snackbar 向用户显示简短消息。与通知不同,消息会在短时间后自动消失。Snackbar 非常适合用户无需采取行动的简短消息。例如,电子邮件应用可以使用 Snackbar 来告知用户该应用已成功发送电子邮件。

使用 CoordinatorLayout

Snackbar 已附加到视图中。如果 Snackbar 附加到派生自 View 类的任何对象(例如任何常见的布局对象),则会提供基本功能。不过,如果 Snackbar 附加到 CoordinatorLayout,则 Snackbar 会获得其他功能:

  • 用户可以通过滑动来关闭 Snackbar。
  • 当 Snackbar 出现时,布局会移动其他界面元素。 例如,如果布局具有 FloatingActionButton,则当布局显示 Snackbar 时,会将按钮向上移动,而不是在按钮顶部绘制 Snackbar。图 1 显示了此效果。

CoordinatorLayout 类提供的功能是 FrameLayout 的超集。如果您的应用已使用 FrameLayout,您可以将该布局替换为 CoordinatorLayout,以启用完整的 Snackbar 功能。如果您的应用使用其他布局对象,请将现有布局元素封装在 CoordinatorLayout 中,如以下示例所示:

<androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/myCoordinatorLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- Here are the existing layout elements, now wrapped in
         a CoordinatorLayout. -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <!-- ...Toolbar, other layouts, other elements... -->

    </LinearLayout>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

为 CoordinatorLayout 设置 android:id 标记。 显示消息时,您需要布局的 ID。

图 1. 当 Snackbar 出现时,CoordinatorLayout 会将 FloatingActionButton 向上移动。

显示消息

显示消息分为两步。首先,您需要使用消息文本创建一个 Snackbar 对象。然后,您调用该对象的 show() 方法,向用户显示消息。

创建 Snackbar 对象

通过调用静态 Snackbar.make() 方法来创建 Snackbar 对象。创建 Snackbar 时,请指定其显示的消息以及显示消息的时长:

val mySnackbar = Snackbar.make(view, stringId, duration)
查看
要将 Snackbar 附加到的视图。该方法会从传递的视图开始向上搜索视图层次结构,直到找到 CoordinatorLayout 或窗口装饰的内容视图为止。 通常,传递封装内容的 CoordinatorLayout 会更简单。
stringId
您要显示的消息的资源 ID。可以是格式化文本或非格式化文本。
时长
显示消息的时长。可以是 LENGTH_SHORT 或 LENGTH_LONG。

向用户显示消息

创建 Snackbar 后,调用其 show() 方法向用户显示 Snackbar:

mySnackbar.show()

系统不会同时 显示多个 Snackbar 对象,因此如果视图当前正在显示另一个 Snackbar, 系统会将您的 Snackbar 排入队列,并在当前 Snackbar 过期或被关闭后显示您的 Snackbar。

如果您想向用户显示消息,但不需要调用任何 Snackbar 对象的实用程序方法,则在调用 show() 后,无需保留对 Snackbar 的引用。因此,通常会使用方法链在一条语句中创建并显示 Snackbar:

Snackbar.make(
    findViewById(R.id.myCoordinatorLayout),
    R.string.email_sent,
    Snackbar.LENGTH_SHORT
).show()