Android Snackbar使用详解

作者: android 发布时间: 2017-07-05 浏览: 5585 次 编辑

Snackbar是Android Support Design Library库中的一个控件,可以在屏幕底部快速弹出消息,跟Toast的使用方法类似,显现效果比toast好(个人意见

1,Snackbar基本介绍和使用方法

首先看一下官方的介绍:

Snackbars provide lightweight feedback about an operation. They show a brief message at the bottom of the screen on mobile and lower left on larger devices. Snackbars appear above all other elements on screen and only one can be displayed at a time.

They automatically disappear after a timeout or after user interaction elsewhere on the screen, particularly after interactions that summon a new surface or activity. Snackbars can be swiped off screen.

Snackbars can contain an action which is set via setAction(CharSequence, android.view.View.OnClickListener).

To be notified when a snackbar has been shown or dismissed, you can provide a Snackbar.Callback via addCallback(BaseCallback).

简单的说Snackbar就是一个类似Toast的快速弹出消息提示的控件,手机上显示在底部,大屏幕设备显示在左侧。但是在显示上比Toast丰富,也提供了于用户交互的接口

使用Snackbar要导入com.android.support:design库。

Snackbar显示在所有屏幕其它元素之上(屏幕最顶层),同一时间只能显示一个snackbar。

Snackbar的基本使用很简单,与Toast类似。

Snackbar.make(view, message_text, duration)
   .setAction(action_text, click_listener)
   .show();

make(View view, CharSequence text, int duration)方法是生成Snackbar的。

Snackbar需要一个控件容器view用来容纳,官方推荐使用CoordinatorLayout来确保Snackbar和其他组件的交互,比如滑动取消Snackbar、Snackbar出现时FloatingActionButton上移。

显示时间duration有三种类型LENGTH_SHORT、LENGTH_LONG和LENGTH_INDEFINITE。

setAction()方法可设置Snackbar右侧按钮,增加进行交互事件。如果不使用setAction()则只显示左侧message。

Snackbar.make(view, "显示在左侧的message", Snackbar.LENGTH_LONG)
        .setAction("右侧显示action文本", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "你点击了action事件", Toast.LENGTH_SHORT).show();
            }
        }).show();


如果你想在Snackbar的显示时或消失时做些什么,可以调用Snackbar的addCallback()方法 (setCallback方法API 25.1.0过时了)。

Snackbar.make(view, "显示在左侧的message", Snackbar.LENGTH_LONG)
    .addCallback(new BaseTransientBottomBar.BaseCallback<Snackbar>() {
    @Override
    public void onShown(Snackbar transientBottomBar) {
        super.onShown(transientBottomBar);
        Toast.makeText(MainActivity.this, "SnackBar 开始显示了", Toast.LENGTH_SHORT).show();
    }
    @Override
    public void onDismissed(Snackbar transientBottomBar, int event) {
        super.onDismissed(transientBottomBar, event);
        Toast.makeText(MainActivity.this, "SnackBar 要消失了", Toast.LENGTH_SHORT).show();
    }
}).show();


2,改变SnackBar的显示样式

Snackbar和Toast的默认样式都很单一,但是有时我们希望把不同类型信息区别显示,从而使用户更容易注意到提示信息。所以使Snackbar变色是一个好主意。

Snackbar的官方API只提供了setActionTextColor()这个方法修改Action的文字颜色,那如何改变样式呢,我们在源码中先看一下SnackBar的make()方法

make()方法源码:

public static Snackbar make(@NonNull View view, @NonNull CharSequence text, @Duration int duration) {
    final ViewGroup parent = findSuitableParent(view);
    if (parent == null) {
        throw new IllegalArgumentException("No suitable parent found from the given view. "
                + "Please provide a valid view.");
    }
    final LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    final SnackbarContentLayout content = (SnackbarContentLayout) inflater
            .inflate( R.layout.design_layout_snackbar_include, parent, false);
    final Snackbar snackbar = new Snackbar(parent, content, content);
    snackbar.setText(text);
    snackbar.setDuration(duration);
    return snackbar;
}

在make方法中我们可以看到初始化了一个Snackbar,并且为Snackbar添加了一个SnackbarContentLayout(查看源码可以看到这个布局文件继承自LinearLayout)的布局,而SnackbarContentLayout加载了R.layout.design_layout_snackbar_include布局文件,这个文件就是Snackbar显示出来的布局文件,那我们先看看这个文件

design_layout_snackbar_include.xml文件源码:

<?xml version="1.0" encoding="utf-8"?>
<view
    xmlns:android="http://schemas.android.com/apk/res/android"
    class="android.support.design.internal.SnackbarContentLayout"
    android:theme="@style/ThemeOverlay.AppCompat.Dark"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom">
    <TextView
        android:id="@+id/snackbar_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:paddingTop="@dimen/design_snackbar_padding_vertical"
        android:paddingBottom="@dimen/design_snackbar_padding_vertical"
        android:paddingLeft="@dimen/design_snackbar_padding_horizontal"
        android:paddingRight="@dimen/design_snackbar_padding_horizontal"
        android:textAppearance="@style/TextAppearance.Design.Snackbar.Message"
        android:maxLines="@integer/design_snackbar_text_max_lines"
        android:layout_gravity="center_vertical|left|start"
        android:ellipsize="end"
        android:textAlignment="viewStart"/>
    <Button
        android:id="@+id/snackbar_action"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="@dimen/design_snackbar_extra_spacing_horizontal"
        android:layout_marginStart="@dimen/design_snackbar_extra_spacing_horizontal"
        android:layout_gravity="center_vertical|right|end"
        android:minWidth="48dp"
        android:visibility="gone"
        android:textColor="?attr/colorAccent"
        style="?attr/borderlessButtonStyle"/>
</view>

由命名可知,以snackbar_text为名的TextView就是Snackbar左侧的message,以 snackbar_action为名的Button就是Snackbar 右侧的action。

好了,现在我们就可以通过上面的id来随意的操作这两个控件的属性了,直接上代码。

Snackbar snackbar = Snackbar.make(view, "显示在左侧的message", Snackbar.LENGTH_LONG)
        .setAction("右侧显示action文本", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "你点击了action事件", Toast.LENGTH_SHORT).show();
            }
        });
//获取Snackbar的view
View snackbarContent = snackbar.getView();
if (snackbarContent != null) {
    //修改Snackbar的背景色
    snackbarContent.setBackgroundColor(Color.parseColor("#0000ff"));
    //获取Snackbar的message控件,修改字体颜色和大小
    TextView snackbarText = ((TextView) snackbarContent.findViewById(R.id.snackbar_text));
    snackbarText.setTextColor(Color.parseColor("#ff0000"));
    snackbarText.setTextSize(16);
    //获取Snackbar的aciton控件,修改字体颜色和大小
    Button snackbarAction = ((Button) snackbarContent.findViewById(R.id.snackbar_action));
    snackbarText.setTextColor(Color.parseColor("#ff0000"));
    snackbarText.setTextSize(16);
}
snackbar.show();


好了,今天就写到这里了,当然也可以把Snackbar改变成自定义的样式,只要把Snackbar 的布局替换掉就可以了,我就不写了,大家自己去研究吧

大家也可以封装成工具类,方便后边使用,这个很简单吧,大家自己动手做吧

最后是代码地址喽:https://image.niwoxuexi.com/download/blogSnackbarDemo.zip