Android Snackbar

半腔热情 提交于 2019-12-03 02:27:34

Snackbar与Toast

Snackbars provide brief feedback about an operation through a message at the bottom of the screen.

Snackbars contain a single line of text directly related to the operation performed. They may contain a text action, but no icons.

Toasts (Android only) are primarily used for system messaging. They also display at the bottom of the screen, but may not be swiped off-screen.

Snackbar 可以自定义action,swiped off-screen。但是也有缺陷:

1. 多次show会产生多个实例(可以通过程序回收)

2. 同一时间只能显示一个snackbar

Snackbar使用的时候需要一个控件容器用来容纳Snackbar.官方推荐使用CoordinatorLayout。

Having a CoordinatorLayout in your view hierarchy allows Snackbar to enable certain features, such as swipe-to-dismiss and automatically moving of widgets like FloatingActionButton.

使用方法

1. gradle添加依赖 

compile 'com.android.support:design:22.2.0'

2. layout中添加容器,如上所述,推荐使用CoordinateLayout。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="测试"
        android:id="@+id/btnTest"/>
    <android.support.design.widget.CoordinatorLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

3. show

Snackbar.make(coordinateLayout, "Snackbar Test", Snackbar.LENGTH_SHORT)
       .setAction("点击我", new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               // 添加你的代码
           }
       })
       .show();

其中coordinateLayout是容器,如例子layout中的@+id/container。

更多

可以对 snackbar 设置一些额外的配置,例如setActionTextColorsetDuration详见https://developer.android.com/reference/android/support/design/widget/Snackbar.html

Snackbar.make(coordinateLayout, "Snackbar Test", Snackbar.LENGTH_SHORT)
       .setAction("点击我", new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               // 添加你的代码
           }
       })
       .setActionTextColor(R.color.material_blue)
       .setDuration(4000).show();

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!