如何获得Android手机屏幕的真实宽度和高度
来源:爱站网时间:2020-11-04编辑:网友分享
对于Android的初学者来说,要实现一个功能可能要研究很常时间的代码,这也降低了我们的工作效率,今天爱站技术频道小编教大家如何获得Android手机屏幕的真实宽度和高度,进入下文认真学习一下吧!
对于Android的初学者来说,要实现一个功能可能要研究很常时间的代码,这也降低了我们的工作效率,今天爱站技术频道小编教大家如何获得Android手机屏幕的真实宽度和高度,进入下文认真学习一下吧!
分享给大家供大家参考,具体如下:
WindowManager w = activity.getWindowManager();
Display d = w.getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
d.getMetrics(metrics);
// since SDK_INT = 1;
widthPixels = metrics.widthPixels;
heightPixels = metrics.heightPixels;
try {
// used when 17 > SDK_INT >= 14; includes window decorations (statusbar bar/menu bar)
widthPixels = (Integer) Display.class.getMethod("getRawWidth").invoke(d);
heightPixels = (Integer) Display.class.getMethod("getRawHeight").invoke(d);
} catch (Exception ignored) {
}
try {
// used when SDK_INT >= 17; includes window decorations (statusbar bar/menu bar)
Point realSize = new Point();
Display.class.getMethod("getRealSize", Point.class).invoke(d, realSize);
widthPixels = realSize.x;
heightPixels = realSize.y;
} catch (Exception ignored) {
}
补:改进版 (弥补了原先非支持版本的一些异常):
WindowManager w = activity.getWindowManager();
Display d = w.getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
d.getMetrics(metrics);
// since SDK_INT = 1;
widthPixels = metrics.widthPixels;
heightPixels = metrics.heightPixels;
// includes window decorations (statusbar bar/menu bar)
if (Build.VERSION.SDK_INT >= 14 && Build.VERSION.SDK_INT = 17)
try {
Point realSize = new Point();
Display.class.getMethod("getRealSize", Point.class).invoke(d, realSize);
widthPixels = realSize.x;
heightPixels = realSize.y;
} catch (Exception ignored) {
}
请大家在学习的时候一定要参考爱站技术频道介绍的如何获得Android手机屏幕的真实宽度和高度,更多的专业知识请关注js.aizhan.com哦。
