我有一个模式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
添加到此 View 。问题就在这里,当用户在移动对话框后移开手指时,MotionEvenet.ACTION_UP 不会调用。那么有什么想法吗?谢谢。
最佳答案
如果您想修改底部对话框 fragment 中的 Bottom Sheet 对话框行为,请使用以下命令:
@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)
}
}
})
}
这将帮助您将展开和隐藏设置为 false,并且您还可以将自定义尺寸设置为展开。
关于java - 如何更改BottomSheetDialogFragment的BottomSheetBehavior?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61027310/