查漏补缺:Android 获取屏幕宽高的方法统计

获取设备屏幕高度是个很重要的属性,把它记录下来

一,通过Display获取

    Display display = getWindowManager().getDefaultDisplay();
    int width = display.getWidth();
    int height = display.getHeight();
    Log.d(TAG, "width = " + width + ",height = " + height);
    //width = 1440,height = 2768

二,通过Point获取

    Display defaultDisplay = getWindowManager().getDefaultDisplay();
    Point point = new Point();
    defaultDisplay.getSize(point);
    int x = point.x;
    int y = point.y;
    Log.i(TAG, "x = " + x + ",y = " + y);
    //x = 1440,y = 2768

三,通过Rect获取

    Rect outSize = new Rect();
    getWindowManager().getDefaultDisplay().getRectSize(outSize);
    int left = outSize.left;
    int top = outSize.top;
    int right = outSize.right;
    int bottom = outSize.bottom;
    Log.d(TAG, "left = " + left + ",top = " + top + ",right = " + right + ",bottom = " + bottom);
    //left = 0,top = 0,right = 1440,bottom = 2768

四,通过屏幕DisplayMetrics

    DisplayMetrics outMetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
    int widthPixels = outMetrics.widthPixels;
    int heightPixels = outMetrics.heightPixels;
    Log.i(TAG, "widthPixels = " + widthPixels + ",heightPixels = " + heightPixels);
    //widthPixels = 1440, heightPixels = 2768

五,新的通过point获取RealSize

    Point outSize = new Point();
    getWindowManager().getDefaultDisplay().getRealSize(outSize);
    int x = outSize.x;
    int y = outSize.y;
    Log.w(TAG, "x = " + x + ",y = " + y);
    //x = 1440,y = 2960

六,新的通过屏幕DisplayMetrics

    DisplayMetrics outMetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getRealMetrics(outMetrics);
    int widthPixel = outMetrics.widthPixels;
    int heightPixel = outMetrics.heightPixels;
    Log.w(TAG, "widthPixel = " + widthPixel + ",heightPixel = " + heightPixel);
    //widthPixel = 1440,heightPixel = 2960

这几个方法主要区别在于,获取屏幕哪部分区域,现在设备类型很多,手机,平板,刘海屏,虚拟按键,手表,电视等都使用的android系统,大家在使用过程中需要注意不同方法对应的设备取值不同会有差异,手里设备有限无法一一测试,有小伙伴发现了可以在评论留言,我会及时更新,帮助其他人避开弯路!

发布了58 篇原创文章 · 获赞 10 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_34203714/article/details/100710512