Dialog的大小除了可以引用自定义布局外, 还可以通过代码进行固定:
mDialog.show();
// Window window = mDialog.getWindow();
// window.getDecorView().setPadding(0, 0, 0, 0);
WindowManager.LayoutParams attrs = mDialog.getWindow().getAttributes();
//attrs.setTitle("Title");
attrs.width = WindowManager.LayoutParams.WRAP_CONTENT;// attrs.width =580;
attrs.height = WindowManager.LayoutParams.WRAP_CONTENT;// attrs.height = 600;
mDialog.getWindow().setAttributes(attrs);
还有一种, 可以通过手机设备的像素密度进行动态设置对话框的宽与高, 不至于同样像素的内容在分辨率不同的设备上出现不同的效果:
private static void setLayoutParams(Context context,Dialog dialog){
WindowManager.LayoutParams attrs = dialog.getWindow().getAttributes();
final float scale = context.getResources().getDisplayMetrics().density;
attrs.width = (int)(193*scale+0.5f);
attrs.height =(int)(200*scale+0.5f);
dialog.getWindow().setAttributes(attrs);
}
文中所给的193与200是通过测试,显示的一个比较好的值. 不同的设备与不同的需求可以进行数值的调试.
参考以下资料:
1、px :是屏幕的像素点
2、dp :一个基于density的抽象单位,如果一个160dpi的屏幕,1dp=1px
3、转换方式如下
public class DensityUtil {
/**
* 根据手机的分辨率从 dp 的单位 转成为 px(像素)
*/
public static int dip2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
/**
* 根据手机的分辨率从 px(像素) 的单位 转成为 dp
*/
public static int px2dip(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
}