也许我找到了解决方案。我在我的视图组中添加了框架布局。谢谢节食者_h
为覆盖 IntercepterTouchEvent 创建自定义 Framelayout 类
private class InterceptTouchEventLayout extends FrameLayout {
Snackbar mSnackbar;
public InterceptTouchEventLayout(Context context) {
super(context);
setLayoutParams(new CoordinatorLayout.LayoutParams(
CoordinatorLayout.LayoutParams.MATCH_PARENT,
CoordinatorLayout.LayoutParams.MATCH_PARENT));
}
public void setSnackbar(Snackbar snackbar) {
mSnackbar = snackbar;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
int action = ev.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
if (mSnackbar != null && mSnackbar.isShown()) {
mSnackbar.dismiss();
}
break;
}
return super.onInterceptTouchEvent(ev);
}
}
我的xml:
<FrameLayout
...>
<ScrollView .../>
<FrameLayout .../>
</FrameLayout>
获取最重要的 FrameLayout
View contentView = this.findViewById(android.R.id.content);
View framLayout = ((ViewGroup) contentView).getChildAt(0);
添加自定义布局的写法
private void addInterceptLayoutToViewGroup(Snackbar snackbar) {
View contentView = this.findViewById(android.R.id.content);
ViewGroup vg = (ViewGroup) ((ViewGroup) contentView).getChildAt(0);
if (!(vg.getChildAt(0) instanceof InterceptTouchEventLayout)) {
InterceptTouchEventLayout interceptLayout =
new InterceptTouchEventLayout(this);
interceptLayout.setSnackbar(snackbar);
for (int i = 0; i < vg.getChildCount(); i++) {
View view = vg.getChildAt(i);
vg.removeView(view);
interceptLayout.addView(view);
}
vg.addView(interceptLayout, 0);
} else {
InterceptTouchEventLayout interceptLayout =
(InterceptTouchEventLayout) vg.getChildAt(0);
interceptLayout.setSnackbar(snackbar);
}
}
所以,我可以这样使用!!!
Snackbar snackbar = Snackbar.make(this.findViewById(android.R.id.content), "text", Snackbar.LENGTH_INDEFINITE)
.setAction("action", new View.OnClickListener() {
@Override
public void onClick(View v) {
//...
}
});
snackbar.show();
addInterceptLayoutToViewGroup(snackbar);
老实说,我的解决方案改变了视图树(?)。之后,我的 xml 可能是..
<FrameLayout
...>
<InterceptTouchEventLayout
...>
<ScrollView .../>
<FrameLayout .../>
</InterceptTouchEventLayout>
</FrameLayout>