五、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.lxweimin.com/p/3596988b74ca)
#### 二、[Toolbar的梳理與使用](http://www.lxweimin.com/p/e90fa1074359)
#### 三、[TextInputLayout的梳理與使用](http://www.lxweimin.com/p/1d43eb8b54ec)
#### 四、[FloatingActionButton的梳理與使用](http://www.lxweimin.com/p/1b87b4eb1fac)
#### 五、[Snackbar的梳理與使用](http://www.lxweimin.com/p/e8712186243a)
#### 六、[CardView的梳理與使用](http://www.lxweimin.com/p/249c274a70ae)
#### 七、[BottomSheetDialog的梳理與使用](http://www.lxweimin.com/p/016534448bfe)
#### 八、[TabLayout的梳理與使用](http://www.lxweimin.com/p/77cd67f4e2da)
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,527評論 6 544
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,687評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,640評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,957評論 1 318
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,682評論 6 413
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 56,011評論 1 329
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 44,009評論 3 449
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 43,183評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,714評論 1 336
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,435評論 3 359
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,665評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,148評論 5 365
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,838評論 3 350
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,251評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,588評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,379評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,627評論 2 380

推薦閱讀更多精彩內容