1

I want to change the hex color value of a color variable and colorAccent color defined in the colors.xml file by MainActivity.java code.

What code should I write in the java file inside a method or a switch or if/else statement to change it?

enter image description here

SHOONYA
  • 352
  • 3
  • 14
  • 3
    The resources are immutable, so you can't change their values. Why do you need to change them tho ? – Software Dev Jan 08 '20 at 09:24
  • 1
    put if-else use the different color key. you can not change the color value – Tejas Jan 08 '20 at 09:24
  • you could create different theme configuration, and switch between them programmatically . – nazmul Jan 08 '20 at 09:30
  • @Aousafrashid so the resources are immutable, then i will define a different color variable with desired value to it but what about the colorAccent ? how do I change it Via java code – SHOONYA Jan 08 '20 at 09:35
  • @nazmul how do I create a different theme configuration ? please write an answer or refer me one – SHOONYA Jan 08 '20 at 09:37
  • @TejuVishwakarma ok so i can define the color to a different color key for views but how do I change the color of colorAccent ? I don't know how to define a different color key for colorAccent – SHOONYA Jan 08 '20 at 09:41
  • https://stackoverflow.com/a/2483001/3237884, check this answer for reference – nazmul Jan 08 '20 at 10:02

2 Answers2

4

You should use themes and styles for changing color values. See: Styles and Themes

Basically, you should declare the color in styles.xml:

<style name="GreenText" parent="TextAppearance.AppCompat">
    <item name="android:textColor">#00FF00</item>
</style>

<style name="RedText" parent="TextAppearance.AppCompat">
    <item name="android:textColor">#ff0000</item>
</style>

Then declare which theme to use in onCreate (before setContentView()):

 switch (theme) {
     case 1:
         setTheme(R.style.Green);
         break;
     case 2:
         setTheme(R.style.Red);
         break;
 }

Edit: You can change the theme during onCreate() only - If you want to change it afterwards, during runtime, you will have to recreate your activity by calling recreate()

  • what about the colorAccent color? how to change it programatically – SHOONYA Jan 08 '20 at 09:40
  • as @Black mamba posted, all color values are hardcoded. Therefore a way for you to deal with what you want to do is to prepare multiple different themes and switch them. – Kamil Vilím Jan 08 '20 at 09:42
0

Unfortunately all color values (and other resources) inside the resources directory are hardcoded as static final ints. This means there is no way to change the values at runtime. You can however use one of the previously suggested solutions or have a look at this excellent

here's exaplained

Black mamba
  • 462
  • 4
  • 15