我想禁用滑动来解除我尝试过的snackbar
行为
很多事情对我来说都不起作用,任何一个人都建议我如何实现这一目标,
这是我试过的
final Snackbar snackbar = Snackbar
.make(main_content, getResources().getString(R.string.no_internet), Snackbar.LENGTH_INDEFINITE);
snackbar.setActionTextColor(Color.BLACK);
View snackbarView = snackbar.getView();
snackbarView.setBackgroundColor(Color.WHITE);
TextView textView = (TextView) snackbarView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.BLACK);
// textView.setTypeface(fontLight);
snackbar.setAction("RETRY", new View.OnClickListener() {
@Override
public void onClick(View view) {
apiAccess();
}
});
snackbar.show();
这是我的小吃吧代码,我尝试了两件事:
1
((android.support.design.widget.CoordinatorLayout.LayoutParams) snackbar.getView().getLayoutParams()).setBehavior(null);
在snackbar.show();
方法之后但没有奏效。
2
main_content.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
ViewGroup.LayoutParams lp = main_content.getLayoutParams();
if (lp instanceof CoordinatorLayout.LayoutParams) {
((CoordinatorLayout.LayoutParams) lp).setBehavior(new DisableSwipeBehavior());
main_content.setLayoutParams(lp);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
main_content.getViewTreeObserver().removeOnGlobalLayoutListener(this);
} else {
//noinspection deprecation
main_content.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
}
});
public class DisableSwipeBehavior extends SwipeDismissBehavior<Snackbar.SnackbarLayout> {
@Override
public boolean canSwipeDismissView(@NonNull View view) {
return false;
}
}
在上面代码main_content
是我的CoordinatorLayout。
答案 0 :(得分:1)
试试这个:
Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout) snackbar.getView();
snackbar.setDuration(Snackbar.LENGTH_INDEFINITE);
snackbar.show();
layout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
ViewGroup.LayoutParams lp = layout.getLayoutParams();
if (lp instanceof CoordinatorLayout.LayoutParams) {
((CoordinatorLayout.LayoutParams) lp).setBehavior(new DisableSwipeBehavior());
layout.setLayoutParams(lp);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
layout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
} else {
//noinspection deprecation
layout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
}
});
DisableSwipeBehavior的地方:
public class DisableSwipeBehavior extends SwipeDismissBehavior<Snackbar.SnackbarLayout> {
@Override
public boolean canSwipeDismissView(@NonNull View view) {
return false;
}
}