一、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可以通過向右滑動取消。