How to handle notch(display cutout) in android API lower than 28?

前端 未结 4 1241
你的背包
你的背包 2020-12-16 14:12

Android added notch support on API 28, but how to handle it on devices running API 27 (Honor 10, Huawei P20, etc.) ?

I was trying to use DisplayCutoutCompat<

4条回答
  •  臣服心动
    2020-12-16 14:42

    I had similar issue, and had to use reflection to access what I need. My problem was that I had some calculations depending on screen size and while not accessing the notch space, the calculations were wrong and code didn't work well.

        public static final String CLASS_DISPLAY_CUTOUT = "android.view.DisplayCutout";
        public static final String METHOD_GET_DISPLAY_CUTOUT = "getDisplayCutout";
        public static final String FIELD_GET_SAFE_INSET_TOP = "getSafeInsetTop";
        public static final String FIELD_GET_SAFE_INSET_LEFT = "getSafeInsetLeft";
        public static final String FIELD_GET_SAFE_INSET_RIGHT = "getSafeInsetRight";
        public static final String FIELD_GET_SAFE_INSET_BOTTOM = "getSafeInsetBottom";
    
    
        try {
                WindowInsets windowInsets = activity.getWindow().getDecorView().getRootWindowInsets();
                if (windowInsets == null) {
                    return;
                }
                Method method = WindowInsets.class.getMethod(METHOD_GET_DISPLAY_CUTOUT);
                Object displayCutout = method.invoke(windowInsets);
                if (displayCutout == null) {
                    return;
                }
                Class clz = Class.forName(CLASS_DISPLAY_CUTOUT);
                int top = (int) clz.getMethod(FIELD_GET_SAFE_INSET_TOP).invoke(displayCutout);
                int left = (int) clz.getMethod(FIELD_GET_SAFE_INSET_LEFT).invoke(displayCutout);
                int right = (int) clz.getMethod(FIELD_GET_SAFE_INSET_RIGHT).invoke(displayCutout);
                int bottom = (int) clz.getMethod(FIELD_GET_SAFE_INSET_BOTTOM).invoke(displayCutout);
                Rect rect = new Rect(left, top, right, bottom);
    
            } catch (Exception e) {
                Log.e(TAG, "Error when getting display cutout size");
            }
    

提交回复
热议问题