skip to Main Content
View decorView = getWindow().getDecorView();
decorView.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {

        @Override
        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {
              if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                    DisplayCutout displayCutout = insets.getDisplayCutout();
                    if (displayCutout != null) {
                        // Display cutout is present
                        Log.d(TAG, "Display cutout detected");
                        Toast.makeText(MainActivity.this, "Detected", Toast.LENGTH_LONG).show();
                    } else {
                        // No display cutout
                        Log.d(TAG, "No display cutout detected");
                        Toast.makeText(MainActivity.this, " Not Detected", Toast.LENGTH_LONG).show();
                    }
                }
                return insets.consumeSystemWindowInsets();
            }

I’m using the above code to detect if a cutout is present or not. But for the devices with cutout/ notch present it is still showing that there is no display cutout present.

2

Answers


  1. Use the following code to get display cutouts (with approriate null checks):

    // Get the actual screen size in pixels
    DisplayMetrics metrics = new DisplayMetrics();
    MainActivity.getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
    int width = metrics.widthPixels;
    int height = metrics.heightPixels;
    // if there are no cutouts, top and left offsets are zero
    int top = 0;
    int left = 0;
    // get any cutouts
    DisplayCutout displayCutout = MainActivity.getWindowManager().getDefaultDisplay().getCutout();
    // check if there are any cutouts
    if (displayCutout != null && displayCutout.getBoundingRects().size() > 0) {
        // add safe insets together to shrink width and height
        width -= (displayCutout.getSafeInsetLeft() + displayCutout.getSafeInsetRight());
        height -= (displayCutout.getSafeInsetTop() + displayCutout.getSafeInsetBottom());
        // NOTE:: with LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES, we can render on the whole screen
        // NOTE::    and therefore we CAN and MUST set the top/left offset to avoid the cutouts.
        top = displayCutout.getSafeInsetTop();
        left = displayCutout.getSafeInsetLeft();
    }
    
    Login or Signup to reply.
  2. You have to set layoutInDisplayCutoutMode first. Add this line before get getDisplayCutout

    getWindow().getAttributes().layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search