I have an activity in which I need to change the color of several elements, so doing it one by one can be a bit tedious. These elements share a common denominator which is the color from the corresponding resource.
Is it possible to change the value of such a resource programmatically?
For example, make:
<color name="colorTitle">#212121</color>
then take another hexadecimal value and apply it to all elements that have colorTitle .
Resources such as
R.colors
are generated at compile time as constants so you won't be able to change them at run time. What you can do is create a function that returns the color you want and all views that require changing the color dynamically get it via the method.For example. Create a
Activity
base class for your entire application that contains the following method:So whenever a view requires the color to change, then you just assign the result of the function to it, for example even
TextView
:In the example, the color of the
TextView
are based on the state of the variablecolorClaro
, if it changes, when the view is loaded again, all the elements that get the color of the function will change.The state that will decide whether to take one color or the other you could save in a
SharePreferences
database or according to your choice.NO, Items defined in resource files eg
colors.xml
, are read-only.As an option you can add other related colors, and use the one you decide for example: