Android Snackbar

Snackbar與Toasthtml

Snackbars provide brief feedback about an operation through a message at the bottom of the screen.java

Snackbars contain a single line of text directly related to the operation performed. They may contain a text action, but no icons.android

Toasts (Android only) are primarily used for system messaging. They also display at the bottom of the screen, but may not be swiped off-screen.ide

Snackbar 能夠自定義action,swiped off-screen。可是也有缺陷:測試

1. 屢次show會產生多個實例(能夠經過程序回收)gradle

2. 同一時間只能顯示一個snackbargoogle

Snackbar使用的時候須要一個控件容器用來容納Snackbar.官方推薦使用CoordinatorLayout。spa

Having a CoordinatorLayout in your view hierarchy allows Snackbar to enable certain features, such as swipe-to-dismiss and automatically moving of widgets like FloatingActionButton.code

使用方法

1. gradle添加依賴 component

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

2. layout中添加容器,如上所述,推薦使用CoordinateLayout。

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

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="測試"
        android:id="@+id/btnTest"/>
    <android.support.design.widget.CoordinatorLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

3. show

Snackbar.make(coordinateLayout, "Snackbar Test", Snackbar.LENGTH_SHORT)
       .setAction("點擊我", new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               // 添加你的代碼
           }
       })
       .show();

其中coordinateLayout是容器,如例子layout中的@+id/container。

更多

能夠對 snackbar 設置一些額外的配置,例如setActionTextColorsetDuration詳見https://developer.android.com/reference/android/support/design/widget/Snackbar.html

Snackbar.make(coordinateLayout, "Snackbar Test", Snackbar.LENGTH_SHORT)
       .setAction("點擊我", new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               // 添加你的代碼
           }
       })
       .setActionTextColor(R.color.material_blue)
       .setDuration(4000).show();
相關文章
相關標籤/搜索