Looking at the Gravity
object, you need to translate the XML descriptors into the object's constants:
center_vertical
-> Gravity.CENTER_VERTICAL
Constant Value: 16 (0x00000010)
start
-> Gravity.START
Constant Value: 8388611 (0x00800003)
You add them and you get your value (8388627).
The reverse can be done with logical operations in 3 steps:
- eliminate the generic flags (like
Gravity.RELATIVE_LAYOUT_DIRECTION
)
- progressively eliminate the other flags
- recombine the generic and normal flags back (like
LEFT + RELATIVE_LAYOUT_DIRECTION = START
) - this is optional
My approach would be:
Create a Map<int, String> modifiers
Create a Map<int, String> flags
Create a List<int> components
Populate modifiers with all generic flags and their corresponding strings
Use something like (flag > 0x0010000 && (flag & 0x0000FFFF == 0))
Populate flags with all other elements ( < 0x0010000)
// Note: Don't populate modifiers with elements like Gravity.START
int value = my_value_to_parse
for (int i in modifiers.keys()) {
if (value & i > 0) {
components.add(i)
value = value & !i
}
}
// Same code for the flags
for (int i in flags.keys())
...
// One can add logic for merging composite flags here
// And add the components to a string
String result = ""
for (int component: components) {
if (modifiers.containsKey(component))
result += modifiers.get(component)
else if (flags.containsKey(component))
result += flags.get(component)
result += "|"
// Return everything except last | character
return result.substring(0, result.length() - 2)
You can use this question to generate a Map
of strings and codes.
To convert the list to a string you can also create a List and use a Join
(guava) or Apache Commons.