五、Snackebar

一、Snackbar的基础使用

通过调用Snackbar的静态方法make来创建一个Snackbar对象,我们后续通过这个对象操作;

private void initSnackbar() {
        //通过调用静态方法make创建Snackbar对象;
        snackbar = Snackbar.make(mCoordinatorLayout, "MessageView", Snackbar.LENGTH_INDEFINITE);
        //给actionView的字体设置颜色
        snackbar.setActionTextColor(getResources().getColor(R.color.colorAccent));
        snackbar.setAction("actionView", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(SnackBarActivity.this, "点击了actionview", Toast.LENGTH_SHORT).show();
            }
        });
        //显示snackbar
        snackbar.show();
    }
Snackbar的简单实用

从上面可以看得出,MessageView的颜色和Snackbar的背景不能动态设置,只能设置Actionview的字体颜色,并且可以给actionView添加监听事件;

  • 1.显示Snackbar的时候调用 snackbar.show()方法即可;
  • 2.隐藏Snackbar有四种方式:
  • 1.直接从左往右滑动Snackbar即可,因为Snackbar实现了SwipeDismissBehavior;在测试中发现--如果使用此方式隐藏后,再次调用show()方法无效果
  • 2.点击actionView;
  • 3.主动调用dismiss方法;
    1. 通过setDuration()方法,设置显示持续时间;

二 、Snackbar进阶使用
首先看下Snackbar的make方法源码

    @NonNull
    public static Snackbar make(@NonNull View view, @NonNull CharSequence text,
            @Duration int duration) {
        //找到传进来view的父控件,如果是CoordinatorLayout或者是R.id.content布局就停止寻找,
否则一直寻找,直到找到根布局;findSuitableParent()方法见下面源码;
        final ViewGroup parent = findSuitableParent(view);
        final LayoutInflater inflater = LayoutInflater.from(parent.getContext());
         //实例化出SnackbarContentLayout
        final SnackbarContentLayout content =
                (SnackbarContentLayout) inflater.inflate(
                        R.layout.design_layout_snackbar_include, parent, false);
        //根据父View和SnackbarContentLayout得到Snackbar对象
        final Snackbar snackbar = new Snackbar(parent, content, content);
        //设置Snackbar的MessageView文本信息
        snackbar.setText(text);
        //设置Snackbar的显示持续时间
        snackbar.setDuration(duration);
        return snackbar;
    }

下面是fitSuitableParent()方法:可以看到它其实是从我们在make方法中传入的View作为起点,沿着整个View树向上寻找,如果发现是CoordinatorLayout或者到达了R.id.content,那么就停止寻找,否则将一直到达View树的根节点为止,所以,如果我们的CoordinatorLayout不是全屏的话,那么Snackbar有可能不是弹出在整个屏幕的底部,经测试确实如此;

    private static ViewGroup findSuitableParent(View view) {
        ViewGroup fallback = null;
        do {
            if (view instanceof CoordinatorLayout) {
                // We've found a CoordinatorLayout, use it
                return (ViewGroup) view;
            } else if (view instanceof FrameLayout) {
                if (view.getId() == android.R.id.content) {
                    // If we've hit the decor content view, then we didn't find a CoL in the
                    // hierarchy, so use it.
                    return (ViewGroup) view;
                } else {
                    // It's not the content view but we'll use it as our fallback
                    fallback = (ViewGroup) view;
                }
            }

            if (view != null) {
                // Else, we will loop and crawl up the view hierarchy and try to find a parent
                final ViewParent parent = view.getParent();
                view = parent instanceof View ? (View) parent : null;
            }
        } while (view != null);

        // If we reach here then we didn't find a CoL or a suitable content view so we'll fallback
        return fallback;
    }

通过查看Design包下的res文件下的布局文件:desgin_layout_snackbar_include.xml可以发现,此布局文件中只有两个控件,一个是TextView,一个Button,也就是SnackbarContentLayout包含了一个TextView和一个Button,对应上文中提到的MessageView和ActionView;布局如下:
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>

如果获得SnackbarContentLayout对象,就能改变Snackbar背景和MessageView的字体颜色;那么如何获得SnackbarContentLayout对象呢?
先来看下Snackbar的构造函数:


    private Snackbar(ViewGroup parent, View content, ContentViewCallback contentViewCallback) {
        //调用了父类的构造函数
        super(parent, content, contentViewCallback);
    }
//父类(BaseTransientBottomBar)的构造函数
protected BaseTransientBottomBar(@NonNull ViewGroup parent, @NonNull View content,
            @NonNull ContentViewCallback contentViewCallback) {
        //主要的代码
        mView = (SnackbarBaseLayout) inflater.inflate(
                R.layout.design_layout_snackbar, mTargetParent, false);
        //通过调用此方法,将SnackbarContentLayout添加的mView中
        mView.addView(content);
    }
//父类(BaseTransientBottomBar)提供一个得到mView的方法
 /**
     * Returns the {@link BaseTransientBottomBar}'s view.
     */
    @NonNull
    public View getView() {
        return mView;
    }

那么我们就可以通过getView方法获得mView,也就能够得到SnackbarcontentLayout

  • 1.改变Snackbar背景
    public void changeSnackbarBackground() {
        View view = snackbar.getView();
        view.setBackgroundColor(getResources().getColor(android.R.color.holo_green_light));
    }

效果图:

改变背景的效果图.png
  • 2.改变MessageView的字体颜色
//改变MessageView字体颜色
    public void changeMessageViewTextColor(){
        ViewGroup view = (ViewGroup) snackbar.getView();
        SnackbarContentLayout childAt = (SnackbarContentLayout) view.getChildAt(0);
        //得到MessageView
        TextView messageView = (TextView) childAt.getChildAt(0);
        messageView.setTextColor(getResources().getColor(android.R.color.white));
    }
~~~

[github仓库](https://github.com/wangluAndroid/MaterialDesignProject.git)

#### 相关内容:
#### 一、[CoordinatorLayout的梳理与使用](http://www.jianshu.com/p/3596988b74ca)
#### 二、[Toolbar的梳理与使用](http://www.jianshu.com/p/e90fa1074359)
#### 三、[TextInputLayout的梳理与使用](http://www.jianshu.com/p/1d43eb8b54ec)
#### 四、[FloatingActionButton的梳理与使用](http://www.jianshu.com/p/1b87b4eb1fac)
#### 五、[Snackbar的梳理与使用](http://www.jianshu.com/p/e8712186243a)
#### 六、[CardView的梳理与使用](http://www.jianshu.com/p/249c274a70ae)
#### 七、[BottomSheetDialog的梳理与使用](http://www.jianshu.com/p/016534448bfe)
#### 八、[TabLayout的梳理与使用](http://www.jianshu.com/p/77cd67f4e2da)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,298评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,701评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,078评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,687评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,018评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,410评论 1 211
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,729评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,412评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,124评论 1 239
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,379评论 2 242
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,903评论 1 257
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,268评论 2 251
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,894评论 3 233
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,014评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,770评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,435评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,312评论 2 260

推荐阅读更多精彩内容