构建并显示弹出式消息

试试 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 中,如以下示例所示:

<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();