AndroidDev AndroidDev - 3 months ago 14
Android Question

How does this line of code is evaluated in Java (Android)?

I'm working on the android developer tutorial "Using Immersive Full-Screen Mode"

https://developer.android.com/training/system-ui/immersive.html#nonsticky

Everything was ok until I found this code snippet.

private void hideSystemUI() {
// Set the IMMERSIVE flag.
// Set the content to appear under the system bars so that the content
// doesn't resize when the system bars hide and show.
mDecorView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
| View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
| View.SYSTEM_UI_FLAG_IMMERSIVE);
}


And I'm a little bit confused with the setSystemUiVisibility(int) method because I don't know how this condition is evaluated.

Why is this method receiving several integer values?

Maybe it is a very basic concept about java language but I had never used or seen it before.

Answer

setSystemUiVisibility is actually receiving 1 integer. What you're seeing here are bit flags. All those View constants you see are combined using bitwise or.

The idea is that a flag represents a toggle: on or off, 1 or 0. A typical way of representing that is with a boolean which has values true and false. But a boolean takes up 4 bytes (for simplicity), which is 32 bits. Well this boolean could actually be used to represent 32 different flags then, with 32 places for 1 or 0! Same with an integer (of size 4 bytes). So lets use an integer to hold a bunch of flags, and set all of them to 0 initially.

We can then use the bitwise or operator (|, note 1 bar, not 2) to specify which bit flag to set to "true" like so:

00000000 | 00100000 = 00100000
00100000 | 00000001 = 00100001

The second number is showing which flag we want to set as true. Now your variables have the values (from documentation):

View.SYSTEM_UI_FLAG_LAYOUT_STABLE          = 0x0100 = 0000 0001 0000 0000
View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x0200 = 0000 0010 0000 0000
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN      = 0x0400 = 0000 0100 0000 0000
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION        = 0x0002 = 0000 0000 0000 0010
View.SYSTEM_UI_FLAG_FULLSCREEN             = 0x0004 = 0000 0000 0000 0100
View.SYSTEM_UI_FLAG_IMMERSIVE              = 0x0800 = 0000 1000 0000 0000

When you combine them all together with bitwise or, you get 0000 1111 0000 0110 = 0x0F06 = 3846.

Comments