Android DisplayMetrics类获取屏幕大小

DisplayMetrics

 public class DisplayMetrics 
 extends Object  

java.lang.Object 
   ↳ android.util.DisplayMetrics 
是Android提供的记述屏幕的有关信息的一种结构,诸如其尺寸,密度和字体缩放的一般信息。

第一种方法:

WindowManager wm = (WindowManager) context.getSystemService(
       Context.WINDOW_SERVICE);
DisplayMetrics metrics= new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(metric);

第二种方法

DisplayMetrics metrics= new DisplayMetrics();

getWindowManager().getDefaultDisplay().getMetrics(metrics);

第三种方法

DisplayMetric metrics=mContext.getResources().getDisplayMetric();

        //这俩个就是手机屏幕的屏幕分辨率,物理宽高值如1080*1920(ToolBar或ActionBar会占据一定空间,得到的heightPiexls会小一点)
        int width = metrics.widthPixels;  // 表示屏幕的像素宽度,单位是px(像素)
        int height = metrics.heightPixels;  // 表示屏幕的像素高度,单位是px(像素)

        float density = metrics.density;  // 显示器的逻辑密度,Density Independent Pixel(如3.0)

         ( metrics.scaledDensity和metrics.density数值是一样的)
        int densityDpi = metrics.densityDpi;  // 整个屏幕的像素密度DPI(dots per inch每英寸像素数),可以是密度低,密度中等,或者密度高(如240/ 360 / 480)

        float xdpi= metrics.xdpi /表示在X轴方向上每英寸的像素值,X轴方向上的DPI(dots per inch)
        float ydpi= metrics.ydpi //表示在Y轴方向上每英寸的像素值,  Y方向上的DPI

//wm.getDefaultDisplay().getHeight();获得的数据和int height = metrics.heightPixels一样,不过getHeight()方法弃用了,建议使用后者

 

 

density详细说明

 

float density

 

The logical density of the display. This is a scaling factor for the Density Independent Pixel unit, where one DIP is one pixel on an approximately 160 dpi screen (for example a 240x320, 1.5"x2" screen), providing the baseline of the system's display. Thus on a 160dpi screen this density value will be 1; on a 120 dpi screen it would be .75; etc.

 

This value does not exactly follow the real screen size (as given by xdpi and ydpi, but rather is used to scale the size of the overall UI in steps based on gross changes in the display dpi. For example, a 240x320 screen will have a density of 1 even if its width is 1.8", 1.3", etc. However, if the screen resolution is increased to 320x480 but the screen size remained 1.5"x2" then the density would be increased (probably to 1.5).

不需要在AndroidManifest.xml文件额外声明 support-screen节点,因为屏幕适配的几种属性值都默认为true。参考官方文档API.

 

转载于:https://www.cnblogs.com/feng-ye/p/5923019.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值