How can I implement BottomSheetDialogFragment with fixed height

前端 未结 3 2226
难免孤独
难免孤独 2021-02-20 05:31

I need to implement BottomSheetDialogFragment and face with the problem. I need that my BottomSheetDialogFragment has fixed height. Does anyone has an

3条回答
  •  暖寄归人
    2021-02-20 06:16

    If the RecyclerView content is filled inside initRecyclerView(contentView); then when showing BottomSheet it's height is well known. To set the height of BottomSheet dynamically and to wrap the content then add global layout listener inside onResume function of the BottomSheetDialogFragment:

    @Override
    public void onResume() {
        super.onResume();
        addGlobaLayoutListener(getView());
    }
    
    private void addGlobaLayoutListener(final View view) {
        view.addOnLayoutChangeListener(new OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                setPeekHeight(v.getMeasuredHeight());
                v.removeOnLayoutChangeListener(this);
            }
        });
    }
    
    public void setPeekHeight(int peekHeight) {
        BottomSheetBehavior behavior = getBottomSheetBehaviour();
        if (behavior == null) {
            return;
        }
        behavior.setPeekHeight(peekHeight);
    }
    
    private BottomSheetBehavior getBottomSheetBehaviour() {
        CoordinatorLayout.LayoutParams layoutParams = (CoordinatorLayout.LayoutParams) ((View) getView().getParent()).getLayoutParams();
        CoordinatorLayout.Behavior behavior = layoutParams.getBehavior();
        if (behavior != null && behavior instanceof BottomSheetBehavior) {
            ((BottomSheetBehavior) behavior).setBottomSheetCallback(mBottomSheetBehaviorCallback);
            return (BottomSheetBehavior) behavior;
        }
        return null;
    }
    

提交回复
热议问题