Get screen width and height in Android

前端 未结 30 4240
野的像风
野的像风 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 09:58

    As an android official document said for the default display use Context#getDisplay() because this method was deprecated in API level 30.

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

    This bowl of code help to determine width and height.

    public static int getWidth(Context context) {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        Display display = context.getDisplay();
        if (display != null) {
            display.getRealMetrics(displayMetrics);
            return displayMetrics.widthPixels;
        }
        return -1;
    }
    

    For the Height:

    public static int getHeight(Context context) {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        Display display = context.getDisplay();
        if (display != null) {
            display.getRealMetrics(displayMetrics);
            return displayMetrics.heightPixels;
        }
        return -1;
    }
    

提交回复
热议问题