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 设置一些额外的配置,例如setActionTextColor
和setDuration
详见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();