Beating the fitsSystemWindows nightmare

Photo by Fotis Fotopoulos on Unsplash

Some things frustrate me in Android development, but nothing quite like the FitSystemWindows API, where everything can go wrong. Not gonna lie but I may have taken too much time to learn how to do it properly without messing the whole app.

FitSystemWindows is the API that enables drawing under the statusbar and the navigation bar usually just applying a simple attribute. It is applied depth-first of the views.

This attribute is usually used when you have collapsing toolbars or want to make a scroll without boundaries.

Let’s start!

To begin with, you have to set the statusbar to be transparent in your themes or styles.

Then, for the layout files, the rule you need to follow is to only add the attribute “android:fitsSystemWindows=true” on the layouts you want to be drawn behind the statusbar.

So in a single activity application, the attribute should only be applied in the root fragment layout and if you have a toolbar, you also need to add it in the AppBarLayout.

If you don’t have a toolbar, just add it to the layout you want to be drawn underneath.

The activity layout should be something like this, without adding any fitsSystemWindows.

If you have a toolbar the fitsSystemWindows attribute should be in the root layout and then in the AppBarLayout

Suggestions

Be careful to not use more than one
app:layout_behavior=”com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior” and other fitsSystemWindows attribute inside each other causes the layout to have padding you can’t remove.

If you need to apply the insets to a view that may have not gotten them or any other reason you can use the following function to do that for you ViewCompat.requestApplyInsets(yourView)

If you need to know the insets to apply a more complex logic like animating a view or setting a view in a certain position you also have the following function that comes very handy.

ViewCompat.setOnApplyWindowInsetsListener(appBarLayout) { view, insets ->
//Do something with the insets
insets
}

You got it!

It can be complex at times and sometimes, the only way to figure it out is with a bit of trial and error so don’t be afraid to get your hands dirty.

Also, try to understand how it really works and for this the best way would be this post by Ian Lake where he explains the functionality in more detail.

If you want I created a simple project with some examples to get you started with it. Feel free to make some experiments and learn how using the attribute in different places has different results.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store