public class CustomCoordinatorLayout extends CoordinatorLayout {
private boolean mIsSnackBar = false;
private View mSnakBarView = null;
private OnSnackBarListener mOnSnackBarListener = null;
public CustomCoordinatorLayout(Context context) {
super(context);
}
public CustomCoordinatorLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if(mIsSnackBar){
// Check whether the snackbar is existed.
// If it is not existed then index of the snackbar is -1.
if(indexOfChild(mSnakBarView) == -1){
mSnakBarView = null;
mIsSnackBar = false;
if(mOnSnackBarListener != null)
mOnSnackBarListener.onDismiss();
Log.d("NEOSARCHIZO","SnackBar is dismissed!");
}
}
}
@Override
public void onMeasureChild(View child, int parentWidthMeasureSpec, int widthUsed, int parentHeightMeasureSpec, int heightUsed) {
super.onMeasureChild(child, parentWidthMeasureSpec, widthUsed, parentHeightMeasureSpec, heightUsed);
// onMeaureChild is called before onMeasure.
// The view of SnackBar doesn't have an id.
if(child.getId() == -1){
mIsSnackBar = true;
// Store the view of SnackBar.
mSnakBarView = child;
if(mOnSnackBarListener != null)
mOnSnackBarListener.onShow();
Log.d("NEOSARCHIZO","SnackBar is showed!");
}
}
public void setOnSnackBarListener(OnSnackBarListener onSnackBarListener){
mOnSnackBarListener = onSnackBarListener;
}
public interface OnSnackBarListener{
public void onShow();
public void onDismiss();
}
}
我使用自定义协调器布局。当显示 Snackbar 时,将调用 CoordinatorLayout 的 onMeasure 和 onMeasureChild。所以我重写了这些方法。
请注意,您必须设置自定义协调器布局的子级 ID。因为我通过id找到了SnackBar的视图。SnackBar 的 id 为 -1。
CustomCoordinatorLayout layout = (CustomCoordinatorLayout)findViewById(R.id.main_content);
layout.setOnSnackBarListener(this);
Snackbar.make(layout, "Hello!", Snackbar.LENGTH_LONG).setAction("UNDO", new View.OnClickListener() {
@Override
public void onClick(View v) {
//TODO something
}
}).show();
在您的活动或片段中实现 OnSnackBarListener。当显示快餐栏时,它将调用 onShow。并且一个被解雇然后它将调用 onDismiss。