Skip to content Skip to sidebar Skip to footer

What Are These Pipe Characters?

I know in java | means inclusive or, which I never really used but now I saw it in this piece of code that I used in my application. Why is it used this way and what does it do ? m

Solution 1:

In android API View.setSystemUiVisibility() is used to modify visibility of various view decorations.

You can select various features using flags.

Different flags have different meaning and they are documented in detail in the official docs: setSystemUiVisibility.

If you are not familiar with bitwise operations you should skim through this first.

This notation is a very common technique which is used to encode "sets" in a single machine word:

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

Mathematically OR-ing machine words which have only one bit set would produce a unique value for every two unique operands. Therefore, if you have a composite value you always can decompose it back to the original values which were used to produce it. The bits must be offset, otherwise there's no way to extract the original values.

If you have two binary values with only one bit set 0001 and 0010 then OR-ing them would produce binary value 0011. Now you can pass that machine word around and then when necessary decompose it back to two original values.

After reading that wikipedia article you should be able to understand how the following works:

int FLAG1 = 0x1; //0001int FLAG2 = 0x2; //0010int FLAG3 = 0x4; //0100// combine using ORint flags = FLAG1 | FLAG3; //==0101 (5)// using + is possible as well but can lead to errors:// flags += FLAG1// flags now is 0110 but you didn't mean to enable FLAG2
...
// remove a flag
flags &= ~FLAG1;
// toggle a flag
flags ^= FLAG3
// decomposeif(flags & FLAG1)
{
    //we know flag1 was set.
}

If you open android docs again you will see that it mentions a constant value in hexadecimal for every flag:

SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION

...

Constant Value: 512 (0x00000200)

SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100 (256)
SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200 (512)

these are used as I described above: value | FLAG requests some feature, value & ~FLAG turns it off, value ^ FLAG toggles it.

Deep inside of android code combined value will be decomposed and various features enabled and disabled based on the flags which you set.

Post a Comment for "What Are These Pipe Characters?"