Android编程获得手机屏幕真实宽高 Android编程实现获得手机屏幕真实宽高的方法

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Android编程获得手机屏幕真实宽高 Android编程实现获得手机屏幕真实宽高的方法

wanqi   2021-03-20 我要评论
想了解Android编程实现获得手机屏幕真实宽高的方法的相关内容吗,wanqi在本文为您仔细讲解Android编程获得手机屏幕真实宽高的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点: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 {
  widthPixels = (Integer) Display.class.getMethod("getRawWidth").invoke(d);
  heightPixels = (Integer) Display.class.getMethod("getRawHeight").invoke(d);
} catch (Exception ignored) {
}
// includes window decorations (statusbar bar/menu bar)
if (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程序设计有所帮助。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们