Android自定义Dialog没有按设置的宽度显示的问题

针对自定义Dialog对话框(可以参考之前的博客)没有按设置的宽度显示的问题,可以采用如下方式解决:

Window window = dialog.getWindow();
WindowManager.LayoutParams lp = window.getAttributes();
//将宽度值dp转px
lp.width = context.getResources().getDimensionPixelOffset(R.dimen.dp_210);
//高度自适应(也可设置为固定值,同宽度设置方法)
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
dialog.getWindow().setAttributes(lp);

即在之前自定义dialog的create()中添加以上代码即可.完整代码如下所示:

public ResultDisplayDialog create() {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            // instantiate the dialog with the custom Theme
            final ResultDisplayDialog dialog = new ResultDisplayDialog(context, R.style.Dialog);

            dialog.setCanceledOnTouchOutside(false);
            View layout = inflater.inflate(R.layout.layout_result_display_dialog, null);
            dialog.addContentView(layout, new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));

            //使dialog宽度按设置的宽度显示,高度自适应
            Window window = dialog.getWindow();
            WindowManager.LayoutParams lp = window.getAttributes();
            lp.width = context.getResources().getDimensionPixelOffset(R.dimen.dp_210);
            lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
            dialog.getWindow().setAttributes(lp);

            //set the dialog icon
            if(iconId > 0){
                ((ImageView) layout.findViewById(R.id.result_display_dialog_icon)).setImageResource(iconId);
            }

            // set the dialog title
            if (title != null) {
                ((TextView) layout.findViewById(R.id.result_display_dialog_title)).setText(title);
            }

            // set the content message
            if (message != null) {
                ((TextView) layout.findViewById(R.id.result_display_dialog_message)).setText(message);
            }

            dialog.setContentView(layout);
            return dialog;
        }

猜你喜欢

转载自blog.csdn.net/u014611408/article/details/86247703
今日推荐