Change hexadecimal of colors.xml android studio

1

I have an activity in which I need to change the color to several elements, so doing it one by one can be a bit tedious. These elements share a common denominator that is the color from the corresponding resource.

Is it possible to change the value of this resource programmatically?

For example, do that:

<color name="colorTitle">#212121</color>

Then take another hexadecimal value and this applies to all elements that have colorTitle .

    
asked by César Alejandro M 29.01.2018 в 03:13
source

2 answers

1

The resources as R.colors are generated at compile time as constants so you can not change them at run time. What you can do is create a function that returns the color you want and that all the views that require changing the color dynamically obtain it through the method.

For example. Create a class Activity base% for your entire application that contains the following method:

public ActivityBase extends AppCompactActivity
{

  private boolean colorClaro = false;

  public int obtenerColorDinamico()
  {
       if(colorClaro)
       {
          return super.getColor(R.colors.color_claro);
       }
       else{
          return super.getColor(R.colors.color_oscuro);
       }
  }
}

So whenever a view requires the color to change, then you only assign the result of the function, for example, even TextView :

public class HomeActivity extends ActivityBase
{
    public void onCreate(Bundle instance)
    {
        setContentView(R.layout.layout_activity);

        myTextView.setTextColor(obtenerColorDinamico());
        //...
    }
}

In the example, the color of the TextView is based on the state of the variable colorClaro , if it changes, when you load the view 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 can save it in a SharePreferences or database or as you choose.

    
answered by 29.01.2018 / 15:01
source
0
  

Is it possible to change the value of this resource programmatically?

NO, Items defined in resource files, for example colors.xml , are read-only.

As an option you can add other related colors, and use the one you decide for example:

<color name="colorTitle">#212121</color>
<color name="colorTitle_claro">#D9D9D9</color>
<color name="colorTitle_oscuro">#0D0D0D</color>
    
answered by 29.01.2018 в 17:44