Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the pipe (|) operator work in Android while setting some properties? [duplicate]

My question may be basic, but I am wondering how the pipe operator works in the following contexts in Android :

We can set multiple input types in layout:

android:inputType = "textAutoCorrect|textAutoComplete"

We can set multiple flags to an intent as follows:

intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION|Intent.FLAG_ACTIVITY_CLEAR_TOP);

Also we can set some properties as follows:

tvHide.setPaintFlags(tvHide.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);

There are multiple instances where we can see such examples in Android.

So my question is, does the | operator act like the bitwise OR operator or does it just concat the results or something else?
If it acts like the bitwise OR operator, then how does it make the expected result correct? Can anybody enlighten me on this?

like image 927
Ichigo Kurosaki Avatar asked Mar 13 '18 12:03

Ichigo Kurosaki


2 Answers

Yes, it is a bitwise inclusive OR operation, primarily used for setting flags (documentation). Consider the following flags:

byte flagA = 0b00000001;
byte flagB = 0b00000100;

If we use the | operator, these two flags are combined:

byte flags = flagA | flagB; // = 0b00000101

Which allows us to set properties or other small bits of status information in a small amount of memory (typically an Integer with most Android flags).

Note that a flag should only ever have one bit "active", i.e. have a value equal to 2^n. This is how we know what flags have been set when we go to check the combined flag holder variable using a bitwise AND operator, e.g.

if ((flags & flagA) == flagA) {
    // Flag A has been set
    ...
}
like image 86
Michael Dodd Avatar answered Sep 23 '22 00:09

Michael Dodd


The pipe in java is the bitwise OR.
When using it in some Android properties, it conceptually does the same thing.
This is that the options separated by the pipe are added.

like image 26
Juan Avatar answered Sep 27 '22 00:09

Juan