1. 程式人生 > >解決BottomSheetDialogFragment show()方法 只展示一部分問題

解決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");