这是一个困扰我很就得问题。今天在我的反复摸索下,总结出了一些个规律。
以下测试以魅族mx5为例。
手机参数:5.5英寸;高:1920;宽1080.
/**
* 获得屏幕的宽度
*
* @param context
* @return
*/
public static int getScreenWidth(Context context) {
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
return (int)(displayMetrics.widthPixels/displayMetrics.density);
}
/**
* 获得屏幕的高度
* @param context
* @return
*/
public static int getScreenHeight(Context context) {
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
return (int)(displayMetrics.heightPixels/displayMetrics.density);
} /**
* 获得屏幕的像素宽度
* @param context
* @return
*/
public static int getScreenWidthPx(Context context) {
DisplayMetrics dm = new DisplayMetrics();
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
windowManager.getDefaultDisplay().getMetrics(dm);
return dm.widthPixels;
} /**
* 获得屏幕的像素高度
* @param context
* @return
*/
public static int getScreenHeightPx(Context context) {
DisplayMetrics dm = new DisplayMetrics();
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
windowManager.getDefaultDisplay().getMetrics(dm);
return dm.heightPixels;
}
执行各个方法,打印log,得到的数值:
02-29 19:59:09.411: E/InsertADActivity(23228): getScreenHeight:640 getScreenWidth:360
02-29 19:59:09.412: E/InsertADActivity(23228): getScreenHeightPx:1920 getScreenWidthPx:1080
/**
* 获取屏幕的密度
*/
public static float getdensity(Context context) {
DisplayMetrics dm = new DisplayMetrics();
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
windowManager.getDefaultDisplay().getMetrics(dm);
LogUtil.e("getdensity", "dm.density:"+dm.density+" dm.densityDpi"+dm.densityDpi);
return dm.density;
}
02-29 20:01:56.685: E/getdensity(23228): dm.density:3.0 dm.densityDpi480
if (relativeLayout.getParent()!=null) {
((ViewGroup) relativeLayout.getParent()).removeView(relativeLayout);
}
insertAdDialog = new AlertDialog.Builder(mActivity).setView(relativeLayout).create();
insertAdDialog.setCanceledOnTouchOutside(false);
insertAdDialog.show();
WindowManager.LayoutParams p = insertAdDialog.getWindow().getAttributes(); // 获取对话框当前的参数值
p.height = (int) (DeviceInfo.getScreenHeightPx(mActivity));
p.width = (int) (DeviceInfo.getScreenWidthPx(mActivity));
insertAdDialog.getWindow().setAttributes(p);
当这样设置时,dialog充满屏幕。