Android编程实现获得手机屏幕真实宽高的方法
程序员文章站
2023-12-10 20:41:28
本文实例讲述了android编程实现获得手机屏幕真实宽高的方法。分享给大家供大家参考,具体如下:
windowmanager w = activity.getwi...
本文实例讲述了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程序设计有所帮助。