Android

Material Design系列教程(3) - Snackba

2018-06-14  本文已影响106人  Whyn

简介

老规矩,先看下文档:

Snackbar

从文档可以看到,Snackbar 为一个操作提供轻量级、快速的反馈。固定在屏幕底部或者大设备左下角,显示时,从下往上滑出进行信息展示。Snackbar 显示在其他 UI 组件上面,并且一次只能显示一个。

可以简单的认为,Snackbar 就是对 Toast 的升级。

注: Snackbar 位于design包中。

Snackbar 使用方法

下面简单介绍下 Snackbar 的使用方法:

    public void onSimpleSnackbarClick(View view) {
        Snackbar.make(view, "This is Snackbar", Snackbar.LENGTH_SHORT).show();
    }

就是这么简单,其基础用法跟 Toast 非常类似。

在查看效果之前,我们先来看下Snack.make方法文档:

make

make方法使 Snackbar 可以显示信息。该方法有3个参数:

好了,现在可以展示下上面代码所显示的效果:

Snackbar_simple

上面代码虽然成功展示了 Snackbar,但是其样式说实话,并不咋样,并且也不具备与用户交互功能。那么,下面我们就试着修改下它的样式与交换把:

    public void onConfirmClick(View view) {
        Snackbar.make(view, "This is Snackbar with confirm button", Snackbar.LENGTH_SHORT)
                .setAction("Confirm", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Snackbar.make(v, "Confirm done!", Snackbar.LENGTH_SHORT).show();
                    }
                }).show();
    }

效果如下:

Snackbar_Action

还可以通过setActionTextColor方法来设置按钮颜色等等。

那么如果我们想修改 Snackbar 文本信息样式(比如文本颜色),可以吗?我们看了以下 Snackbar api,好像并没有提供修改文本颜色功能的接口!因此,我们无法直接修改 Snackbar 文本样式,但是,仔细查看 Snackbar api文档,可以发现,有一个接口(位于其父类中:BaseTransientBottomBar):

image.png

进入源码查看以下:

//BaseTransientBottomBar.java
    final SnackbarBaseLayout mView;
    /**
     * Returns the {@link BaseTransientBottomBar}'s view.
     */
    @NonNull
    public View getView() {
        return mView;
    }

可以知道,getView()返回的是一个SnackbarBaseLayout,那让我们在追踪一下mView的情况,在SnackbarBaseLayout的构造函数中,发现

//SnackbarBaseLayout.java

    /**
     * Constructor for the transient bottom bar.
     *
     * @param parent The parent for this transient bottom bar.
     * @param content The content view for this transient bottom bar.
     * @param contentViewCallback The content view callback for this transient bottom bar.
     */
    protected BaseTransientBottomBar(@NonNull ViewGroup parent, @NonNull View content,
            @NonNull ContentViewCallback contentViewCallback) {
        ...
        ...
        ...
        LayoutInflater inflater = LayoutInflater.from(mContext);
        // Note that for backwards compatibility reasons we inflate a layout that is defined
        // in the extending Snackbar class. This is to prevent breakage of apps that have custom
        // coordinator layout behaviors that depend on that layout.
        mView = (SnackbarBaseLayout) inflater.inflate(
                R.layout.design_layout_snackbar, mTargetParent, false);
        mView.addView(content);
        ...
        ...
        ...
    }

可以看到,mView加载了另一个View,叫content,其是由构造函数传递进来的,所以我们只要找到Snackbar是在哪里被构造的,那么就可以找到这个content的具体情况了。

由于Snackbar构造器是私有的,所以只能在其内部被构造,按我们上面的做法,那么很明显,应该就是在Snackbar.make函数中被构造的把,那么我们就来看下make函数源码把:

    @NonNull
    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;
    }

可以看到,content的布局文件就是design_layout_snackbar_include.xml文件,那么我们就来看下这个文件把:

<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright (C) 2015 The Android Open Source Project
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~      http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
-->

<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的内部布局就是一个 id 为 snackbar_text 的TextView和一个 id 为 snackbar_action 的 Button,其基本布局如下所示:

Snackbar布局

上图中,黑色框代表 Snackbar 对象,红色框代表getView()返回的View,黄色框代表 Snackbar 的内容根布局View(即design_layout_snackbar_include.xml),绿色代表 Snackbar 消息展示的TextView控件,蓝色代表 Snackbar 通过setAction方法进行设置的Button控件。

注: 上图中 SnackbarBaseLayout 也即getView()返回值,继承于 FrameLayoutSnackbarContentLayout也即 Snackbar 的内容布局,继承于LinearLayout

因此,我们只需通过getView(),得到根View,然后通过findViewById就可以找到内部的TextViewButton了。代码如下:

    public void onChangeTextColor(View view) {
        Snackbar sb = Snackbar.make(view, "About to change text color", Snackbar.LENGTH_LONG);
        TextView tv = sb.getView().findViewById(R.id.snackbar_text);
        tv.setTextColor(Color.YELLOW);
        sb.show();
    }

效果如下:

Snackbar_changeTextColor

可以看到,我们的确成功改变了文本信息颜色。

注: 我们通过setAction设置的其实就是 snackbar_action 这个Button,因此,如果多次调用setAction,那么只有最后一次设置生效 ^-^

前面我们查看Snackbar.make方法文档时,其最底下有一段话:

make

Snackbar 会根据你传递的View,自动向上遍历找到一个合适的ViewGroup作为自己的父View,从而让自己能显示出来。只要 Snackbar 遍历找到 CoordinatorLayout或者contentView时,选取成功。Snackbar 显示规则为固定在ViewGroup的底部向上滑动进行展示。

所以,如果我们想让 Snackbar 显示在任意一个View的底部,只需用CoordinatorLayout包裹该View,然后传递View实例给Snackbar.make方法即可。

       <android.support.design.widget.CoordinatorLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <Button
                android:layout_marginBottom="60dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:onClick="onBelowMe"
                android:text="snackbar below me" />
        </android.support.design.widget.CoordinatorLayout>

效果如下:

Snackbar_specific_position

其他需要注意事项

Snackbar sb = Snackbar.make(mOpenTv, "消息内容", Snackbar.LENGTH_SHORT);
        sb.setCallback(new Snackbar.Callback() {
            @Override
            public void onDismissed(Snackbar snackbar, int event) {
                super.onDismissed(snackbar, event);
                // Snackbar关闭时回调
            }

            @Override
            public void onShown(Snackbar snackbar) {
                super.onShown(snackbar);
                // Snackbar打开时回调
            }
        });
        sb.show();
image

建议要使用Snackbar的时候最好是以CoordinatorLayout作为根布局,如果以其它RelativeLayout,LinearLayout等作为根布局的话,会出现以下这种情况:

image

FloatingActionButton被遮到了,使用CoordinatorLayout作为根布局可以避免这种情况:

image

参考

Android Snackbar使用方法及小技巧-design

上一篇 下一篇

猜你喜欢

热点阅读