解決BottomSheetDialogFragment show()方法 只展示一部分問題

問題詳細出現以及原因可以參考這篇文章
主要給出解決方法,主要是針對BottomSheetDialogFragment的顯示問題,而非BottomSheetDialog,其實解決方案是類似的。

重寫BottomSheetDialog,重新計算peek高度,具體代碼如下:

public class FixHeightBottomSheetDialog extends BottomSheetDialog {

    private View mContentView;

    public FixHeightBottomSheetDialog(@NonNull Context context) {
        super(context);
    }

    public FixHeightBottomSheetDialog(@NonNull Context context, int theme) {
        super(context, theme);
    }

    @Override
    protected void onStart() {
        super.onStart();
        fixHeight();
    }

    @Override
    public void setContentView(View view) {
        super.setContentView(view);
        this.mContentView = view ;
    }

    @Override
    public void setContentView(View view, ViewGroup.LayoutParams params) {
        super.setContentView(view, params);
        this.mContentView = view;
    }

    private void fixHeight(){
        if(null == mContentView){
            return;
        }

        View parent = (View) mContentView.getParent();
        BottomSheetBehavior behavior = BottomSheetBehavior.from(parent);
        mContentView.measure(0, 0);
        behavior.setPeekHeight(mContentView.getMeasuredHeight());

        CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) parent.getLayoutParams();
        params.gravity = Gravity.TOP | Gravity.CENTER_HORIZONTAL;
        parent.setLayoutParams(params);
    }
}

然後再繼承BottomSheetDialogFragment,重寫onCreateDialog方法,替換爲上面FixHeightBottomSheetDialog,代碼如下:

public class FixBottomSheetDialogFragment extends BottomSheetDialogFragment {

  @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        return new FixHeightBottomSheetDialog(getContext());
    }
}

那麼此時FixBottomSheetDialogFragment.show()就可以顯示全部了,問題解決。

FixBottomSheetDialogFragment fragment = new FixBottomSheetDialogFragment();
fragment.show(getSupportFragmentManager(),"myFragment");
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章