构建并显示弹出式消息

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

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

使用 CoordinatorLayout

Snackbar 已附加到视图中。如果 Snackbar 附加到从 View 类派生的任何对象(例如任何常见的布局对象),那么它便可提供基本功能。不过,如果 Snackbar 附加到 CoordinatorLayoutSnackbar 会获得额外的功能:

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

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

<android.support.design.widget.CoordinatorLayout
    android:id="@+id/myCoordinatorLayout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    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>

</android.support.design.widget.CoordinatorLayout>

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

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

显示消息

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

创建 Snackbar 对象

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

Kotlin

val mySnackbar = Snackbar.make(view, stringId, duration)

Java

Snackbar mySnackbar = Snackbar.make(view, stringId, duration);
视图
要将 Snackbar 附加到的视图。该方法会从传递的视图向上搜索视图层次结构,直至到达 CoordinatorLayout 或窗口装饰的内容视图。通常,传递封装您的内容的 CoordinatorLayout 更为简单。
stringId
您要显示的消息的资源 ID。这可以是设置了格式的文本,也可以是无格式文本。
时长
显示消息的时长。可为 LENGTH_SHORTLENGTH_LONG

向用户显示消息

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

Kotlin

mySnackbar.show()

Java

mySnackbar.show();

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

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

Kotlin

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

Java

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