1.1下面代码是设置无效
public void showDialog(Context context, String msg) {
DisplayMetrics dm = getResources().getDisplayMetrics();
int width = dm.widthPixels;
if (context == null) {
return;
}
View view = LayoutInflater.from(context).inflate(R.layout.layout_dialog, null);
TextView tvMsg = view.findViewById(R.id.tvMsg);
tvMsg.setText(msg);
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("提示")
.setView(view)
.setCancelable(false)
;
alertDialog = builder.create();
alertDialog.setCanceledOnTouchOutside(false);
android.view.WindowManager.LayoutParams params = alertDialog.getWindow().getAttributes();
Log.d("Tag","width---->"+width);
int width2= (int) (width * 0.5);
Log.d("Tag","width2---->"+width2);
params.width = (int) (width*0.8);
params.height =(int) (width*0.65);;
// dialog.getWindow().setAttributes(params);
alertDialog.getWindow().setAttributes(params);
alertDialog.show();
}
效果如下
![](https://img.haomeiwen.com/i6361543/90b9f42f0ae2c80f.png)
1.2下面是设置生效的代码
public void showDialog(Context context, String msg) {
DisplayMetrics dm = getResources().getDisplayMetrics();
int width = dm.widthPixels;
if (context == null) {
return;
}
View view = LayoutInflater.from(context).inflate(R.layout.layout_dialog, null);
TextView tvMsg = view.findViewById(R.id.tvMsg);
tvMsg.setText(msg);
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("提示")
.setView(view)
.setCancelable(false)
;
alertDialog = builder.create();
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.show();
android.view.WindowManager.LayoutParams params = alertDialog.getWindow().getAttributes();
Log.d("Tag","width---->"+width);
int width2= (int) (width * 0.5);
Log.d("Tag","width2---->"+width2);
params.width = (int) (width*0.8);
params.height =(int) (width*0.65);;
// dialog.getWindow().setAttributes(params);
alertDialog.getWindow().setAttributes(params);
}
效果如下:
![](https://img.haomeiwen.com/i6361543/87e1d9e71f746604.png)
总结,先 alertDialog.show(); 然后 alertDialog.getWindow().setAttributes(params);就设置了宽度和高度,顺序错了,就设置失效了
网友评论