Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify Hex Color Value in Android Metadata

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:

android:value description

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.

like image 637
Phil Avatar asked Apr 30 '26 16:04

Phil


2 Answers

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" />

enter image description here

like image 125
Phil Avatar answered May 03 '26 08:05

Phil


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

like image 30
Brian Attwell Avatar answered May 03 '26 06:05

Brian Attwell