Android Design Support Library系列之五:Snackbar的使用

一、Snackbar介紹

Snackbar作為Android Design Support Library中的一員,使用時并不需要在布局文件中聲明,直接在java代碼中使用就可以了。
使用前添加依賴:

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

Snackbar效果:
1)和Toast 一樣,Snackbar能彈出一條消息
2)一小段時間之后、或者用戶與屏幕觸發(fā)交互,Snackbar 會自動消失
3)一個時刻只能有唯一一個 Snackbar 顯示
4)和Toast 不同的是,Snackbar 可以設(shè)置一個Action與用戶發(fā)生交互

二、Snackbar簡單使用

慣例,給出官方文檔
Toast大家都使用過,像下面這樣:

Toast.makeText(mContext, "Toast", Toast.LENGTH_SHORT).show();

Snackbar使用和Toast極其相似:

Snackbar.make(view, "Snackbar", Snackbar.LENGTH_SHORT).show();

ok,來看一下Snackbar的簡單使用:
布局文件

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

    <Button
        android:id="@+id/bt"
        android:text="苦海,泛起愛恨"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</RelativeLayout>

java代碼

public class MainActivity extends AppCompatActivity {

    private Button bt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bt = (Button) findViewById(R.id.bt);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Snackbar.make(bt,"Snackbar",Snackbar.LENGTH_SHORT).show();
            }
        });
    }
}

效果圖



這里我通過點擊Button,彈出Snackbar(不要管Button的內(nèi)容,那只是我正在聽的歌詞......)

同Toast使用差不多,Snackbar使用時也需要3個參數(shù),第二個參數(shù)、第三個參數(shù)和Toast一樣,分別是:顯示的文本、時間,不同的是Toast第一個參數(shù)是Context,而Snackbar第一個參數(shù)需要的是一個View對象。

三、Snackbar與用戶交互

與Toast不同的是,Snackbar可以與用戶發(fā)生交互,只要給它設(shè)置一個Action就可以了。

Snackbar.make(bt,"Snackbar",Snackbar.LENGTH_SHORT).
    setAction("交互", new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(MainActivity.this,"白云外",Toast.LENGTH_SHORT).show();
          }
  }).show();

當然,如果你不喜歡鏈式的寫法,可以拆開:

Snackbar mSnackbar = Snackbar.make(bt, "Snackbar", Snackbar.LENGTH_SHORT);
mSnackbar.setAction("交互", new View.OnClickListener() {
         @Override
          public void onClick(View v) {
             Toast.makeText(MainActivity.this,"白云外",Toast.LENGTH_SHORT).show();
          }
});
mSnackbar.show();

效果圖:


四、更改Snackbar樣式

1、修改Action中字體顏色
Action中字體顏色默認使用theme中的colorAccent顏色:

 <item name="colorAccent">@color/colorAccent</item>

Snackbar提供了下面這個方法來修改Action中字體顏色

setActionTextColor()
    Snackbar mSnackbar = Snackbar.make(bt, "Snackbar", Snackbar.LENGTH_SHORT);
    mSnackbar.setAction("交互", new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(MainActivity.this,"白云外",Toast.LENGTH_SHORT).show();
        }
    });
    mSnackbar.setActionTextColor(Color.WHITE);
    mSnackbar.show();

效果圖:


2、修改Snackbar背景及提示消息字體顏色
Snackbar并沒有直接提供方法來設(shè)置背景、消息字體顏色的方法,不過Snackbar提供了一個方法來返回一個View對象:

Snackbar.getView()

那么這個View對象代表著什么呢?觀看源碼

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

看到源碼之后發(fā)現(xiàn):原來Snackbar 顯示的內(nèi)容是一個布局填充而來的,接著我又找到那個布局:

<?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>

一看,原來消息是一個TextView,Action按鈕是一個Button,看到這,我頓時知道該怎么做了O(∩_∩)O
這不就是一個布局文件嗎,想要設(shè)置什么直接findViewById找到那個組件直接設(shè)置不就可以了...

Snackbar mSnackbar = Snackbar.make(bt, "Snackbar", Snackbar.LENGTH_SHORT);
mSnackbar.setAction("交互", new View.OnClickListener() {
     @Override
     public void onClick(View v) {
         Toast.makeText(MainActivity.this, "白云外", Toast.LENGTH_SHORT).show();
     }
});
 mSnackbar.setActionTextColor(Color.WHITE);

View view = mSnackbar.getView();
view.setBackgroundColor(Color.parseColor("#ff0099cc"));
TextView tv = (TextView) view.findViewById(R.id.snackbar_text);
tv.setTextColor(Color.GREEN);
mSnackbar.show();

ok,效果很滿意!更多的樣式可以自己去設(shè)置,反正不就是一個TextView和一個Button嗎O(∩_∩)O

五、Snackbar設(shè)置回調(diào)
mSnackbar.setCallback(new Snackbar.Callback(){
       @Override
       public void onShown(Snackbar sb) {
           super.onShown(sb);
           Toast.makeText(MainActivity.this,"onShown",Toast.LENGTH_SHORT).show();
       }
       @Override
       public void onDismissed(Snackbar transientBottomBar, int event) {
          super.onDismissed(transientBottomBar, event);
          Toast.makeText(MainActivity.this,"onDismissed",Toast.LENGTH_SHORT).show();
       }
});

Snackbar可以設(shè)置一個回調(diào),里面有兩個方法:Snackbar顯示的時候調(diào)用、Snackbar消失的時候調(diào)用。


六、Snackbar在CoordinateorLayout容器中

Snackbar需要一個容器,而這個容器官方推薦的CoordinatorLayout,觀看Snackbar的源碼,發(fā)現(xiàn):
Snackbar 會遍歷視圖樹找到一個合適的容器作為載體,而這個載體首選的就是CoordinatorLayout。

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

    private static ViewGroup findSuitableParent(View view) {
        ViewGroup fallback = null;
        //遍歷視圖樹
        do {
            if (view instanceof CoordinatorLayout) {
                // We've found a CoordinatorLayout, use it      首選是CoordinatorLayout作為載體
                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;
    }

那么使用CoordinatorLayout作為載體有什么好處呢?
我在布局文件中又加入了一個FloatingActionButton浮在右下角:

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

    <Button
        android:id="@+id/bt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="苦海,泛起愛恨" />

    <android.support.design.widget.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:src="@mipmap/add" />

</RelativeLayout>

可以看見,Snackbar把FloatingActionButton擋住了,這對用戶來說體驗很不好.

那么使用CoordinatorLayout試試看,CoordinatorLayout是什么呢?
CoordinatorLayout是Android Design Support Library中另外一個組件,后面會單獨寫一篇文章來介紹它,其本質(zhì)是一個超級FrameLayout,主要是作為根標簽使用,協(xié)調(diào)各個子布局。

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/bt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="苦海,泛起愛恨" />

    <android.support.design.widget.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right|bottom"
        android:src="@mipmap/add" />

</android.support.design.widget.CoordinatorLayout>

可以看見,使用CoordinatorLayout之后,Snackbar彈出的時候,F(xiàn)loatingActionButton會自動上升,而且Snackbar可以通過向右滑動取消。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,825評論 6 546
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 99,814評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,980評論 0 384
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 64,064評論 1 319
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,779評論 6 414
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 56,109評論 1 330
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 44,099評論 3 450
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 43,287評論 0 291
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,799評論 1 338
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 41,515評論 3 361
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,750評論 1 375
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,221評論 5 365
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 44,933評論 3 351
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,327評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,667評論 1 296
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,492評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,703評論 2 380

推薦閱讀更多精彩內(nèi)容