Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting the value for custom Attribute android

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.

like image 815
Sarthak Gandhi Avatar asked Aug 15 '26 16:08

Sarthak Gandhi


1 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;
    }

    ...

}
like image 75
Mehrdad Avatar answered Aug 17 '26 07:08

Mehrdad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!