Is there a way to override Android's platform attribute value at the app level?

Viewed 173

I have a custom viewholder class that gets a color from an attribute in the android namespace in the constructor:

int mDefaultPrimaryColor = GetColor(context, android.R.attr.colorPrimary);

....

public static int getColor(Context context, int attr)
{
    TypedArray ta = context.obtainStyledAttributes(new int[]{attr});
    int color = ta.getColor(0, 0);
    ta.recycle();
    return color;
}

Later on the bind method eventually sets the color:

someTextView.setTextColor(mDefaultPrimaryColor);

I would like to override the android.R.attr.colorPrimary value in my app through XML without modifying Java code so that the value is different than the one being set in the SDK.

I tried to override this value in my themes.xml:

<resources>
   <style name="MyAppTheme" parent="@android:Theme.DeviceDefault.NoActionBar">
       <item name="android:colorPrimary">@color/my_color</item>
   </style>
</resources>

However, the color I am seeing in the Android emulator is not the color I have set for my_color. Is there a way to override the android.R.attr.colorPrimary with a color I defined in my app? What am I doing wrong?

EDIT: The theme is already set in the manifest file. Updated the code snippet to be more exact.

2 Answers

Your code doesn't go quite far enough to get the color code. Try this:

// Extract the color attribute we are interested in.
TypedArray a = context.obtainStyledAttributes(new int[]{android.R.attr.colorPrimary});
// From the TypedArray retrive the value we want and default if it is not found.
int defaultColor = a.getColor(0, 0xFFFFFF);
// Make sure to recycle the TypedArray.
a.recycle();

Now in your theme/style, you can specify something like the following:

<item name="android:colorPrimary">@android:color/holo_blue_light</item>

which is

<!-- A light Holo shade of blue. Equivalent to #ff33b5e5. -->
<color name="holo_blue_light">#ff33b5e5</color>

You would, of course, have to apply this color as needed.

You can create a separate theme with changed attribute value then pass the theme to a view passing the ContextThemeWrapper(context, R.style.new_theme) as a context.

Check the docs: https://developer.android.com/reference/android/view/ContextThemeWrapper

UPD: it is surely possible to set the colorPrimary in theme as you tried. You need to add

<application
    ...
    android:theme="@style/MyAppTheme"
    ...

to AndroidManifest.xml.

Related