Setting the value for custom Attribute android

Viewed 1342

I have a custom attribute say like this :

<attr name="colorPrimarySdk" format="color"/>
<attr name="colorSecondarySdk" format="color"/>
<attr name="colorAccentSdk" format="color"/>

And I am using them in my styles like this:

<style name="MyTheme" parent="Theme.AppCompat.Light.NoActionBar">
     <item name="colorPrimary">?colorPrimarySdk</item>
     <item name="colorPrimaryDark">?colorSecondarySdk</item>
     <item name="colorAccent">?colorAccentSdk</item>
</style>

Now what I want is to set the value of my attributes dynamically from the code like, say :

colorPrimarySdk.value = myCustomColor

I have already tried using TypedValue and accessing the attribute itself. If anyone can help changing the value for my custom attribute, that would be a great help. Thanks in advance.

2 Answers

it's hard :)

colors.xml:

    <?xml version="1.0" encoding="utf-8"?>
      <resources>
      <color name="your_special_color">#FF0099CC</color>
    </resources>

Res.java:

public class Res extends Resources {

    public Res(Resources original) {
        super(original.getAssets(), original.getDisplayMetrics(), original.getConfiguration());
    }

    @Override public int getColor(int id) throws NotFoundException {
        return getColor(id, null);
    }

    @Override public int getColor(int id, Theme theme) throws NotFoundException {
        switch (getResourceEntryName(id)) {
            case "your_special_color":
                // You can change the return value to an instance field that loads from SharedPreferences.
                return Color.RED; // used as an example. Change as needed.
            default:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    return super.getColor(id, theme);
                }
                return super.getColor(id);
        }
    }
}

BaseActivity.java

public class BaseActivity extends AppCompatActivity {

    ...

    private Res res;

    @Override public Resources getResources() {
        if (res == null) {
            res = new Res(super.getResources());
        }
        return res;
    }

    ...

}

Define the colors for the specific theme in your colors file:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="my_link_color1">#0077CC</color>
    <color name="my_link_color2">#626262</color>
</resources>

Create file res/values/attrs.xml with contents:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <attr name="myLinkColor" format="reference" />
</resources>

Suppose we have 2 themes in our styles.xml (Theme1 and Theme2) define:

<style name="Theme1" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="myLinkColor">@color/my_link_color1</item>
</style>

<style name="Theme2" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="myLinkColor">@color/my_link_color2</item>
</style>

Use the color in the XML:

android:textColor="?attr/myLinkColor"
Related