Fork me on GitHub

Android获取屏幕密度的四种方法

Android获取屏幕宽度的4种方法

方法一:

1
2
3
WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
int width = wm.getDefaultDisplay().getWidth();
int height = wm.getDefaultDisplay().getHeight();

方法二:

1
2
3
WindowManager wm1 = this.getWindowManager();
int width1 = wm1.getDefaultDisplay().getWidth();
int height1 = wm1.getDefaultDisplay().getHeight();

方法一与方法二获取屏幕宽度的方法类似,只是获取WindowManager 对象时的途径不同。

方法三:

WindowManager manager = this.getWindowManager();
DisplayMetrics outMetrics = new DisplayMetrics();
manager.getDefaultDisplay().getMetrics(outMetrics);
int width = outMetrics.widthPixels;
int height = outMetrics.heightPixels;

方法四:

1
2
3
4
5
Resources resources = this.getResources();
DisplayMetrics dm = resources.getDisplayMetrics();
float density = dm.density;
int width = dm.widthPixels;
int height = dm.heightPixels;

方法三与方法四类似,因 Display.getHeight(),Display.getWidth() 方法过时推荐使用方法三与四

在工具类中封装了一个方法方便经常使用:

1
2
3
4
5
6
public static int[] getScreenSize(Context context) {  
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics);
return new int[]{outMetrics.widthPixels, outMetrics.heightPixels};
}