Android 15 suggests to use enableEdgeToEdge()
, but this removes the top offset of the status bar, causing the main content to overlap with it.
What is the best way to preserve the height of the status bar? Just leave it transparent and render contents below it.
This is my attempt, it works but it’s a lot of code, is there any simpler way?
// in the MainActivity.onCreate():
enableEdgeToEdge()
// the callback will be invoked repeatedly, use this flag to only set the margin-top once
var offsetAdjusted = false
window.decorView.setOnApplyWindowInsetsListener { _, insets ->
if (!offsetAdjusted) {
offsetAdjusted = true
val top = if(Build.VERSION.SDK_INT > Def.ANDROID_10) // for android > 10
insets.getInsetsIgnoringVisibility(WindowInsets.Type.statusBars()).top
else // for android 10
view.rootWindowInsets.stableInsetTop
// the fragment container, which is a FragmentContainerView
val container = binding.root.findViewById<FragmentContainerView>(R.id.nav_host_fragment_activity_main)
val params = container.layoutParams as ViewGroup.MarginLayoutParams
params.topMargin = top
container.layoutParams = params
}
insets
}