最近在做一个东西,要设置AlertDialog的高和宽,却发现不管是改layout还是在代码里改动WindowManager.LayoutParams参数设置都不成功。后来终于找到原因了。
收集的原因如下:
- AlertDialog dialog = builder.setTitle("消息列表")
- .setView(layout)
- .create();
- dialog.show();
-
- dialog.getWindow().setLayout(300, 200);
dialog.show();一定要放在dialog.getWindow().setLayout(300, 200);的前面,否则不起作用。 网上有一种方法是
- WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
- params.width = 300;
- params.height = 200;
- dialog.getWindow().setAttributes(params);
但是dialog.getWindow().setLayout(300, 200);实际上封装了这个方法,setLayout()的源代码如下:
- final WindowManager.LayoutParams attrs = getAttributes();
- attrs.width = width;
- attrs.height = height;
- if (mCallback != null) {
- mCallback.onWindowAttributesChanged(attrs);
- }
所以这两个方法的作用本质上是一样的,都是为AlertDialog设置大小
|