Handle the StatusBar and the NavigationBar in the Activity properly with Windows Insets

Tram Ho

Perhaps when programming Android, we will often encounter many problems with the correct UI display to support all or most of the models on the market today. One of the most difficult problems is probably drawing the UI in full-screen mode, we have to deal with the Status bar and the Navigation Bar overlapping.

You will find it familiar when looking at this illustration:

Or in the Navigation bar

On forums like StackOverFlow, many solutions have been launched, such as the margin toolbar, fab … according to a certain number of dp. This can solve the problem on machines with rabbit ears

But with the machine without rabbit ears, the toolbar will be dropped by a distance, causing loss of aesthetics

General workaround with Window Inset

Window Insets

Describes a set of insets for window content.

To better understand Window Inset, you can refer to d.android at https://developer.android.com/reference/android/view/WindowInsets and today I want to go directly to how you use inset to View margin resolution

You add the above line to the Activity or Fragment’s onResume method. It will set a callback, when the screen has finished calculating the lengths of the navigation bar or status bar, the callback will be called again, along with the inset value. Now you just need to setMargin for toolbar or fab

For generalization, you can write View Extensions:

and done, the code should look like this at the end:

At this point, you have mastered the inset already

Hope the article can help you!

Share the news now

Source : Viblo