lannyf
lannyf

Reputation: 11025

how to dynamically change color using the defined attribute

Having two theme, it can be dynamically switched.

There is a txtColor attribute defined in attrs.xml

<attr name=“txtColor” format="reference" />

in themes.xml, defined the color for the attribute in different theme

<style name=“CustomLight" parent="AppTheme.Base">
    <item name="txtColor”>#000000</item>

<style name=“CustomDark" parent="AppTheme.Base">
    <item name="txtColor”>#ffffff</item>

in layout file, using the attribute is fine

android:textColor="?attr/txtColor"

but got exception when try to use the txtColor attribute

Caused by: android.content.res.Resources$NotFoundException: Resource ID #0x7f010015
txtView.setTextColor(getResources().getColor(R.attr.txtColor));

question: how to change the color dynamically using the attribute?

Upvotes: 2

Views: 3491

Answers (3)

Ashile The Great
Ashile The Great

Reputation: 131

Based on @Iannyf and @Juan Cruz Soler answers, I want to provide a complete answer. First of all generate an xml file called attrs.xml under values section and write your attributes as a color like this:

<resources>
    <declare-styleable name="FullscreenAttrs">
        <attr name="colorPrimary" format="color" />
    </declare-styleable>
</resources>

Then you can use this line of code to apply color to your ImageView as an Icon based on @Iaanyf function:

imageView.setColorFilter(getColorByThemeAttr(context,R.attr.colorPrimary,R.color.your_color));

Upvotes: 0

lannyf
lannyf

Reputation: 11025

I think I found a simpler solution which worked with the existing attrs, here it in case someone is looking for the same, any simpler ones? Thanks!

public static int getColorByThemeAttr(Context context, int attr, int defaultColor) {
    TypedValue typedValue = new TypedValue();
    Resources.Theme theme = context.getTheme();
    boolean got = theme.resolveAttribute(attr, typedValue, true);
    return got ? typedValue.data : defaultColor;
}

Upvotes: 2

Juan Cruz Soler
Juan Cruz Soler

Reputation: 8254

First the attribute format should be "color"

<attr name="txtColor" format="color"/>

Then you can set the color doing this:

int[] attrs = {R.attr.txtColor} ;
try { //getPackageManager() can throw an exeption
    Activity activity = getActivity();
    themeId = activity.getPackageManager().getActivityInfo(activity.getComponentName(), 0).theme;
    TypedArray ta = activity.obtainStyledAttributes(themeId, attrs);
    int color = ta.getColor(0, Color.BLACK); //I set Black as the default color
    txtView.setTextColor(color);
    ta.recycle();
} catch (NameNotFoundException e) {
    e.printStackTrace();
}

Upvotes: 2

Related Questions