解决安卓自定义Dialog不能水平填满屏幕

问题描述:

UI设计,需要展示一个底部充满屏幕的弹出框,但是发现下面和左右都没有充满。
预期:


解决安卓自定义Dialog不能水平填满屏幕_第1张图片

实际:


解决安卓自定义Dialog不能水平填满屏幕_第2张图片

解决方案:

  • 自定义的Dialog中调用父类构造函数时,需要设置style
  • 完整自定义dialog代码如下:
    1.CustDialog.java
package com.cxyzy.simplebottomdialog;

import android.app.Dialog;
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.Gravity;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

public class CustDialog extends Dialog {
    public CustDialog(@NonNull Context context) {
        super(context,R.style.common_dialog);
        setContentView(R.layout.cust_dialog_layout);
        changeDialogStyle();
    }

    /**
     * 设置dialog居下占满屏幕
     */
    private void changeDialogStyle() {
        Window window = getWindow();
        if (window != null) {
            WindowManager.LayoutParams attr = window.getAttributes();
            if (attr != null) {
                attr.height = ViewGroup.LayoutParams.WRAP_CONTENT;
                attr.width = ViewGroup.LayoutParams.MATCH_PARENT;
                attr.gravity = Gravity.BOTTOM;
                window.setAttributes(attr);
            }
        }
    }
}

2.cust_dialog_layout.xml




    

    


3.styles.xml中增加:

    

Demo源代码:

https://gitee.com/cxyzy1/custom_dialog/tree/master/simpleBottomDialog

安卓开发技术分享: https://www.jianshu.com/p/442339952f26

解决安卓自定义Dialog不能水平填满屏幕_第3张图片

你可能感兴趣的:(解决安卓自定义Dialog不能水平填满屏幕)