How to get safe area in android for notch devices

14.5k Views Asked by At

I need to handle layout for notch devices. I know in Ios. I can handle it using safe area in Ios. But in android is there any way to achieve this ?

3

There are 3 best solutions below

0
On

You can use this:

<style name="ActivityTheme">
  <item name="android:windowLayoutInDisplayCutoutMode">
    shortEdges <!-- default, shortEdges, never -->
  </item>
</style>

or the flag

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // or add <item name="android:windowTranslucentStatus">true</item> in the theme
        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)

        val attrib = window.attributes
        attrib.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
    }
}

with styles as

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>

    <!-- Adding fullscreen will just hide the status bar -->
    <!-- <item name="android:windowFullscreen">true</item> -->
</style>
1
On

You need DisplayCutout object for this In yours Activity class (in onCreate()):

WindowManager.LayoutParams lp = this.getWindow().getAttributes();

lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;    

WindowInsets windowInsets = this.getWindow().getDecorView().getRootView().getRootWindowInsets();

DisplayCutout displayCutout = windowInsets.getDisplayCutout();
int bottom = displayCutout.getSafeInsetBottom()

more about this class you can find here: https://developer.android.com/guide/topics/display-cutout and here: https://blog.felgo.com/app-dev-tips-for-devices-with-edge-to-edge-screens-2020

1
On

this will give a Rect with the safe area in top, bottom, left and right. It also has API compatibility check

 public static Rect getSafeArea(@NonNull Activity activity) {
    final Rect safeInsetRect = new Rect();
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
      return safeInsetRect;
    }

    final WindowInsets windowInsets = activity.getWindow().getDecorView().getRootWindowInsets();
    if (windowInsets == null) {
      return safeInsetRect;
    }

    final DisplayCutout displayCutout = windowInsets.getDisplayCutout();
    if (displayCutout != null) {
      safeInsetRect.set(displayCutout.getSafeInsetLeft(), displayCutout.getSafeInsetTop(), displayCutout.getSafeInsetRight(), displayCutout.getSafeInsetBottom());
    }

    return safeInsetRect;
 }