修改DialogFragment的大小和位置

使用DialogFragment的时候,默认在窗口两侧留有padding,位置在屏幕中间,如果想要修改成在底部以及使窗口宽度铺满屏幕可按照以下代码修改

  • 其中在onCreateView中,使用getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE)设置窗口无标题
  • getDialog().getWindow().getAttributes().windowAnimations = R.style.dialogAnim;设置窗口弹出和隐藏动画
  • 在onStart方法中设置窗口的大小和位置
@Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        getDialog().getWindow().getAttributes().windowAnimations = R.style.dialogAnim;
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onStart() {
        super.onStart();
        Window win = getDialog().getWindow();
        // 一定要设置Background,如果不设置,window属性设置无效
        win.setBackgroundDrawable( new ColorDrawable(Color.TRANSPARENT));

        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics( dm );

        WindowManager.LayoutParams params = win.getAttributes();
        params.gravity = Gravity.BOTTOM;
        // 使用ViewGroup.LayoutParams,以便Dialog 宽度充满整个屏幕
        params.width =  ViewGroup.LayoutParams.MATCH_PARENT;
        params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        win.setAttributes(params);
    }

你可能感兴趣的:(修改DialogFragment的大小和位置)