得到屏幕的宽,高
// 过时的方法
screenWidth = getWindowManager().getDefaultDisplay().getWidth();
screenHeight = getWindowManager().getDefaultDisplay().getHeight();
// 分步
WindowManager manager = getActivity().getWindowManager();
screenWidth = display.getWidth();
screenHeight = display.getHeight();
// 新的方法
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
screenWidth = displayMetrics.widthPixels;
screenHeight = displayMetrics.heightPixels;
测试屏幕的宽度
public static void getAndroiodScreenProperty(Context context) {
WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics metrics = new DisplayMetrics();
manager.getDefaultDisplay().getMetrics(metrics);
int width = metrics.widthPixels; // 屏幕宽度
int height = metrics.heightPixels; // 屏幕高度
float density = metrics.density; // 屏幕密度(0.75 / 1.0 / 1.5)
int densityDpi = metrics.densityDpi; // 屏幕密度dpi(120 / 160 / 240)
// 屏幕宽度算法: 屏幕宽度(像素) / 屏幕密度
int screenWidth = (int) (width / density); // 屏幕宽度(dp)
int screenHeight = (int) (height / density); // 屏幕高度(dp)
Log.d("ScreenProperty","屏幕宽度(px):" + width);
Log.d("ScreenProperty","屏幕高度(px):" + height);
Log.d("ScreenProperty","屏幕密度((0.75 / 1.0 / 1.5)):" + density);
Log.d("ScreenProperty","屏幕密度dpi(120 / 160 / 240):" + densityDpi);
Log.d("ScreenProperty","屏幕宽度(dp):" + screenWidth);
Log.d("ScreenProperty","屏幕高度(dp):" + screenHeight);
}
根据屏幕本身,设置Dialog的大小
// 获取屏幕的宽高
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
Window dialogWindow = dialog.getWindow();
WindowManager.LayoutParams params = dialogWindow.getAttributes();
params.height = (int) (displayMetrics.heightPixels * 1.0);
params.width = (int) (displayMetrics.widthPixels * 0.8);
dialogWindow.setAttributes(params);