How to disable BottomSheetDialogFragment dragging

后端 未结 14 1285
猫巷女王i
猫巷女王i 2021-01-31 04:58

How to disable BottomSheetDialogFragment dragging by finger?

I saw similar questions, but they\'re all about BottomSheet not BottomSheetD

14条回答
  •  别那么骄傲
    2021-01-31 05:24

    Having created MyActivity as follows:

    public class MyActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_my);
    
            new MyBottomSheetFragment().show(getSupportFragmentManager(), "tag");
        }
    
        public static class MyBottomSheetFragment extends BottomSheetDialogFragment {
    
            @Override
            public void setupDialog(Dialog dialog, int style) {
                BottomSheetDialog bottomSheetDialog = (BottomSheetDialog) dialog;
                bottomSheetDialog.setContentView(R.layout.sample);
    
                try {
                    Field behaviorField = bottomSheetDialog.getClass().getDeclaredField("behavior");
                    behaviorField.setAccessible(true);
                    final BottomSheetBehavior behavior = (BottomSheetBehavior) behaviorField.get(bottomSheetDialog);
                    behavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
    
                        @Override
                        public void onStateChanged(@NonNull View bottomSheet, int newState) {
                            if (newState == BottomSheetBehavior.STATE_DRAGGING{ 
                                behavior.setState(BottomSheetBehavior.STATE_EXPANDED);
                            }
                        }
    
                        @Override
                        public void onSlide(@NonNull View bottomSheet, float slideOffset) {
                        }
                    });
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    

    Where R.layout.sample is a simple layout:

    
    
    
        
    
        
    
        
    
    
    

    You'll get following output:

    A part of solution is borrowed from this answer.

提交回复
热议问题