Android 調(diào)整Dialog或DialogFragment的寬度

在使用Dialog或者DialogFragment時,難免需要調(diào)整Dialog的寬度,要實現(xiàn)該需求,需要做一下步驟:

(1)在Dialog中使用

在Dialog中使用,需要在Dialog初始化時,加入如下代碼:

        ...
         // 隱藏標(biāo)題欄, 不加彈窗上方會一個透明的標(biāo)題欄占著空間
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

        // 必須設(shè)置這兩個,才能設(shè)置寬度
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.getWindow().getDecorView().setBackgroundColor(Color.TRANSPARENT);

        // 遮罩層透明度
        dialog.getWindow().setDimAmount(0);

        // 設(shè)置寬度
        WindowManager.LayoutParams params = window.getAttributes();
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        params.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
        params.windowAnimations = R.style.bottomSheet_animation;
        dialog.getWindow().setAttributes(params);
       
        // 設(shè)置dialog布局內(nèi)容,這里布局的初始化代碼就不寫出來了
        dialog.setContentView(view, layoutParams)
        dialog.show()

在DialogFragment中,則在onCreateView函數(shù)中,加入上述代碼:


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable           Bundle savedInstanceState) {
        ...
         // 隱藏標(biāo)題欄, 不加彈窗上方會一個透明的標(biāo)題欄占著空間
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);

       // 必須設(shè)置這兩個,才能設(shè)置寬度
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        getDialog().getWindow().getDecorView().setBackgroundColor(Color.TRANSPARENT);

        // 遮罩層透明度
        getDialog().getWindow().setDimAmount(0);

        // 設(shè)置寬度
        WindowManager.LayoutParams params = window.getAttributes();
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        params.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
        params.windowAnimations = R.style.bottomSheet_animation;
        getDialog().getWindow().setAttributes(params);
        return view;
    }

注意必須設(shè)置Dialog的背景為透明,否則設(shè)置寬度的代碼會無效

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容