方式一:
DisplayMetrics dm = new DisplayMetrics();//屏幕度量
getWindowManager().getDefaultDisplay().getMetrics(dm);
int screen_width_1 = dm.widthPixels;//宽度
int screen_height_1 = dm.heightPixels ;//高度
Log.d("AAAAA","第一种方式:screen_width_1="+screen_width_1+",,,,,,,screen_height_1 :"+screen_height_1);
方式二:(推荐这种方式,这种方式计算包含了状态栏和导航栏高度)
Point pt=getMaxWinPoint(this);
int screen_width_2= pt.x;
int screen_height_2 = pt.y;
Log.d("AAAAA","第二种方式:screen_width_2="+screen_width_2+",,,,,,,screen_height_2:"+screen_height_2);
方式三:
DisplayMetrics dm3=getResources().getDisplayMetrics();
int width_3=dm3.widthPixels;
int height_3=dm3.heightPixels;
Log.d("AAAAA","第三种方式:width_3="+width_3+",,,,,,,height_3:"+height_3);
方式四:
View view = getWindow().getDecorView();
int width_4=view.getWidth();
int height_4=view.getHeight();
Log.d("AAAAA","第四种方式:width_4="+width_4+",,,,,,,height_4:"+height_4);
public static final Point getMaxWinPoint(Context context) {
Point screenSize = new Point();
if (context != null) {
if (Build.VERSION.SDK_INT >= 30) {
// For Android 11 (API level 30) and above
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
//获取最大窗口的度量信息,包括该窗口的边界、大小等
WindowMetrics maximumWindowMetrics = windowManager.getMaximumWindowMetrics();
//从 maximumWindowMetrics 中获取窗口的边界,并获取其宽度
screenSize.x = maximumWindowMetrics.getBounds().width();
//从 maximumWindowMetrics 中获取窗口的边界,并获取其高度,这里的高度和宽度即为分辨率
screenSize.y = maximumWindowMetrics.getBounds().height();
} else {
// For versions below Android 11
Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
if (display != null) {
display.getRealSize(screenSize);
}
}
}
return screenSize;
}
以上四种方式,除了方式二,其他三种方式,在横屏或者竖屏,存在获取的宽或高偏小问题,因为减去了状态栏和导航栏的高度