弹出式消息 - Snackbar
弹出式消息有多种,如Toast, Notification, Snackbar等,谷歌Material Design推出后,建议前台中使用Snackbar,后台中使用Notification代替Toast。
Snackbar简介
Snackbar是一种轻量级的消息反馈,将会在位于设备左下角显示一则简短的消息。和Toast一样Snackbar会在短暂显示后自动消失,此外Snackbar还可以和用户交互,如滑动清除,点击事件等。Snackbar的使用需要有几个条件:
BaseTransientBoottomBar.java
final void showView() {
...
// Set view to INVISIBLE so it doesn't flash on the screen before the inset adjustment is
// handled and the enter animation is started
view.setVisibility(View.INVISIBLE);
targetParent.addView(this.view);
...
}
- 由于Toast是基于Window而Snackbar是基于View动态添加到页面,因此Snackbar的父View Group中,必须要有
CoordinatorLayout
- Snackbar必须在前台页面中呈现
显示一则消息
直接看个效果
![](https://zhoux.top/img/markdown/screenshot/20220519214735.gif)
可以看出两点区别:
-
Snackbar只会在前台页面的底部出现,当页面置为后台后无法跟随置为后台;而Toast因为其本质基于Window,因此其行为与前台后台无关;
-
顺序执行两条消息展示时,Snackbar的更新机制是实时更新,而Toast则是要等待前一条消息消失后,才会更新第二条;
-
此外,Snackbar还支持滑动消失;
源码如下:
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"