java - 如何更改 BottomSheetDialogFragment 的 BottomSheetBehavior?
问题描述
我有一个模态BottomSheetDialog
。对话框的当前和默认行为是,当我将对话框向下拖动一半时,它会消失。例如,假设对话框值从 0.0(折叠)到 1.0(展开)。所以当用户将它拖到 0.5 时,它就会崩溃。但是我想要的行为是当我将对话框拖到 0.8 并松开手指时关闭对话框。我怎样才能实现这种行为,有什么办法吗???
另外,我认为只有当我使用任何拖动按钮拖动它时才允许对话框关闭会很棒(大多数情况下它很简单ImageView
)。
所以我想要的是当用户向下移动对话框(拖动)时关闭对话框。
所以我目前的代码是:
public class FiltersBottomSheet extends BottomSheetDialogFragment {
private FragmentFilterBinding binding;
public FiltersBottomSheet() {}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_filter, container, false);
View view = binding.getRoot();
// I'm using data binding
// There is a little logic, but now you don't need it :)
return view;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.getViewTreeObserver()
.addOnGlobalLayoutListener(() -> {
BottomSheetDialog dialog = (BottomSheetDialog) getDialog();
LinearLayout bottomSheet = dialog.findViewById(R.id.bottom_frame);
if (bottomSheet != null) {
BottomSheetBehavior behavior = BottomSheetBehavior.from(bottomSheet);
behavior.setState(BottomSheetBehavior.STATE_EXPANDED);
behavior.addBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
@Override
public void onStateChanged(@NonNull View bottomSheet, int newState) {
//Log.d("Tag___1", "NewState: " + newState);
}
@Override
public void onSlide(@NonNull View bottomSheet, float slideOffset) {
//Log.d("Tag___1", "Offset: " + slideOffset);
}
});
}
});
}
}
所以首先我认为这onSlide()
可以帮助我,但是......这个方法只在用户展开或折叠对话框时调用。因此,例如,当用户触摸对话框并开始向下拖动时,不会调用 onSlide() 方法。你也看到上面我打电话view.getViewTreeObserver()
了,我试图添加onTouchListener
到这个视图中。问题就在这里,MotionEvenet.ACTION_UP
当用户在移动对话框后移开手指时没有调用。那么有什么想法吗?谢谢你。
解决方案
如果要修改底部对话框片段中的底部工作表对话框行为,请使用:
@Override
public void onViewCreated(NotNull@ View view, Nullable@ Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState)
view.getViewTreeObserver()
.addOnGlobalLayoutListener(() -> {
BottomSheetDialog dialog =(BottomSheetDialog) getDialog ()
if (dialog != null) {
FrameLayout bottomSheet = dialog.findViewById (R.id.design_bottom_sheet)
if (bottomSheet != null) {
BottomSheetBehavior behavior = BottomSheetBehavior.from (bottomSheet)
behavior.setState(BottomSheetBehavior.STATE_EXPANDED)
behavior.setSkipCollapsed(true)
behavior.setHideable(false)
}
}
})
}
这将帮助您声明扩展和可隐藏的错误,并且您也可以将自定义大小进行扩展。
推荐阅读
- java - 如何在Java列表中找到所有最大值?
- python - 从 Python 中不同文件中的方法访问类变量
- javascript - 使用 React 的 Django 中的动态 URL 路由
- javascript - 使用 Javascript 变量值或 url 有条件地动态生成或隐藏 html div ID
- mysql - 自动增量低于总行数
- javascript - 为什么在 ejs 中使用 fetch 后没有呈现 HTML 元素?
- android - 无法列出 com.google.android.gms:play-services-location 的版本
- javascript - 如何在静态网站的head标签中动态更改样式表和js文件的基本url
- reactjs - 类型的联合被简化为“从不”打断打字:类型被简化为“从不”,因为属性在某些成分中具有冲突的类型
- reactjs - React & Redux 项目的循环依赖