Get screen width and height in Android

前端 未结 30 4049
野的像风
野的像风 2020-11-22 09:28

How can I get the screen width and height and use this value in:

@Override protected void onMeasure(int widthSpecId, int heightSpecId) {
    Log.e(TAG, \"onM         


        
30条回答
  •  一整个雨季
    2020-11-22 10:21

    Using this code, you can get the runtime display's width & height:

    DisplayMetrics displayMetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    int height = displayMetrics.heightPixels;
    int width = displayMetrics.widthPixels;
    

    In a view you need to do something like this:

    ((Activity) getContext()).getWindowManager()
                             .getDefaultDisplay()
                             .getMetrics(displayMetrics);
    

    In some scenarios, where devices have a navigation bar, you have to check at runtime:

    public boolean showNavigationBar(Resources resources)
    {
        int id = resources.getIdentifier("config_showNavigationBar", "bool", "android");
        return id > 0 && resources.getBoolean(id);
    }
    

    If the device has a navigation bar, then count its height:

    private int getNavigationBarHeight() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            DisplayMetrics metrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(metrics);
            int usableHeight = metrics.heightPixels;
            getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
            int realHeight = metrics.heightPixels;
            if (realHeight > usableHeight)
                return realHeight - usableHeight;
            else
                return 0;
        }
        return 0;
    }
    

    So the final height of the device is:

    int height = displayMetrics.heightPixels + getNavigationBarHeight();
    

提交回复
热议问题