I am working on getting some meta-data working on Android. Most specifically, I am getting application-level meta-data to set a View's background in the following formats:
<meta-data android:name="background"
android:value="red" />
<meta-data android:name="background"
android:resource="@drawable/my_red_background" />
<meta-data android:name="background"
android:value="#FF0000" />
I am using the following code to parse the information:
ApplicationInfo app = getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);
Bundle metaData = app.metaData;
if (metaData != null) {
int resourceID = metaData.getInt("background", -1);
if (resourceID != -1) {
//set the background resource of my view (THIS WORKS)
}
else {
String background = metaData.getString("background");
if (background != null) {
try {
backgroundColor = Color.parseColor(background);
//Set background color (THIS WORKS for 'red', 'blue', etc.)
}
catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
}
If I use the resource method and point it at a drawable, this works. If I use a color string like "red", "blue", "yellow", etc - these also work. However, if I attempt to use a color in any of the formats preceded by a hashmark (#FF0000, #FFFF0000, etc), this does not work, even though the Android Documentation suggests that it should:

Is this a known bug? Is there a simple workaround (other than just using a simple string or a drawable reference)? Or am I missing something? I am using a Asus Transformer Prime 10.1 TF301 Tablet to test (Android 4.0.3).
EDIT
I wanted to note that this is not a problem with Color.parseColor(). Android never enters the statement if (background != null), so somehow the meta data is not getting recognized as a String at all.
Solved! This is not an Android bug, per-se, but rather an Android documentation bug (Surprise, surprise!). A hex color needs an escape character for it to be handled correctly:
<meta-data android:name="background"
android:value="\#FF0000" />

Solution 1) Use a backslash so that value is a string instead of a number.
Solution 2) Instead of calling Color.parseColor(bundle.parseString(..)), just use getInt(..) without a backslash.
Background:
android:value="#aabbgg" is a number
android:value="\#aabbgg" is a string
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With