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程序设计有所帮助。相关阅读:
ASP.NET中TextBox使用Ajax控件显示日期不全的问题解决方法
Win10预览版14342无法安装更新解决方法
苹果os x10.10.3预览大尺寸的JPEG图片时崩溃和重启怎么办
IOS开发之路--C语言数组和字符串
.NET中TextBox控件设置ReadOnly=true后台取不到值三种解决方法
C++实现简单的职工管理系统实训代码
Windows 10 Build 10041:通过修改注册表项手动打开开始菜单跳转列表功能
清除行内元素之间HTML空白的几种解决方案
win10正版和盗版有何不同 windows10正版和盗版的区别介绍
Ubuntu 14.04 LTS中安装fcitx中文输入法的教程
android UI进阶之android中隐藏的layout 抽屉的使用方法
空格在Html中如何表示( 有什么含义)
php中header设置常见文件类型的content-type
Win10移动版红石14322新技能:仅使用3G或4G网络