亲宝软件园·资讯

展开

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

wanqi 人气:0
想了解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程序设计有所帮助。

加载全部内容

相关教程
猜你喜欢
用户评论