参考文章:http://www.open-open.com/lib/view/open1433496206666.html
Snackbar是Toast的升级版,与Toast相比,它额外提供了show和dismiss的判断方法和回调接口。另外,它还提供了增加Button点击的机会,为我们省去了一些需要自定义view才能实现的类似Toast展示效果的提示浮层的工作。
1.首先,引入Android Design Support Library,Android Studio中通过配置依赖来引入:
//build.gradle中的dependencies中增加:
compile 'com.android.support:design:23.4.0'
2.Snackbar的展示效果如图:
它的位置固定,固定出现在屏幕的底部。左侧文案+右侧Action;右侧Action没有时,文案也依然显示在左侧不变。
3.代码调用如下:
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", new View.OnClickListener() {
@Override
public void onClick(View v) {
}
})
.setCallback(new Snackbar.Callback() {
@Override
public void onDismissed(Snackbar snackbar, int event) {
super.onDismissed(snackbar, event);
Log.e("chwn","Snackbar dismiss");
}
@Override
public void onShown(Snackbar snackbar) {
super.onShown(snackbar);
Log.e("chwn","Snackbar show");
}
})
.show();
4.另外,它的Api接口如下:
从中可以看出,除了可以想Toast一样定制文本的内容外,还可以定制Action的文本及文字颜色。
详见:https://developer.android.com/reference/android/support/design/widget/Snackbar.html
Public methods | |
---|---|
void | dismiss() Dismiss the |
int | getDuration() Return the duration. |
View | getView() Returns the |
boolean | isShown() Return whether this |
boolean | isShownOrQueued() Returns whether this |
staticSnackbar | make(View view, CharSequence text, int duration) Make a Snackbar to display a message Snackbar will try and find a parent view to hold Snackbar's view from the value given to |
staticSnackbar | make(View view, int resId, int duration) Make a Snackbar to display a message. |
Snackbar | setAction(int resId, View.OnClickListener listener) Set the action to be displayed in this |
Snackbar | setAction(CharSequence text, View.OnClickListener listener) Set the action to be displayed in this |
Snackbar | setActionTextColor(ColorStateList colors) Sets the text color of the action specified in |
Snackbar | setActionTextColor(int color) Sets the text color of the action specified in |
Snackbar | setCallback(Snackbar.Callback callback) Set a callback to be called when this the visibility of this |
Snackbar | setDuration(int duration) Set how long to show the view for. |
Snackbar | setText(int resId) Update the text in this |
Snackbar | setText(CharSequence message) Update the text in this |
void | show() Show the |