0

I have some problem about apply colors to my app. I want to achieve to get some json from the web, like this:

{
   "colorPrimary": "#45a02c",
   "colorAccent": "#a02c2c",
   "backgroundColor": "#FFFFFF"
}

and store it in a object like ThemeColor, i created. Parsing the json to object is no problem, but now i want to create a method in my ThemeColor class, that will apply the colors of the object to my app, so that my toolbar will colored in this primary color or i can use it with ?attr/colorPrimary .

Is that possible? And what would be a good way to achieve this?

Zoe
  • 27,060
  • 21
  • 118
  • 148
JonasPTFL
  • 189
  • 4
  • 15
  • Possible duplicate of [How to \_really\_ programmatically change primary and accent color in Android Lollipop?](https://stackoverflow.com/questions/25815769/how-to-really-programmatically-change-primary-and-accent-color-in-android-loll) – Dinesh Shingadiya May 27 '19 at 12:44

1 Answers1

1

Define your custom theme inside style.xml and use that inside your activity

style.xml

<style name="CustomTheme" parent="Theme.AppCompat.NoActionBar">
     <!-- Customize your theme here. -->
     <item name="colorPrimary">@color/your_custom_color</item>
     <item name="colorPrimaryDark">@color/your_custom_color_2</item>
     <item name="android:navigationBarColor">@color/your_custom_colot_3</item>
</style>

And use that theme inside your activity

public void onCreate(Bundle savedInstanceState) {
    setTheme(android.R.style.CustomTheme); //here your custom theme
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);
}
Mehul Solanki
  • 1,147
  • 11
  • 15
  • But on this way, i cant change colors to my json colors, right? I mean, the json colors will change at runtime... – JonasPTFL May 27 '19 at 12:50
  • Right, you can't change your `color.xml` using above way. – Mehul Solanki May 27 '19 at 12:51
  • that's because, it's immutable – hemen May 27 '19 at 12:53
  • You may look at [here](https://stackoverflow.com/questions/2482848/how-to-change-current-theme-at-runtime-in-android) and [here](https://stackoverflow.com/questions/4663752/switching-application-wide-theme-programmatically) – Mehul Solanki May 27 '19 at 12:55
  • [Here](https://stackoverflow.com/questions/33987678/programmatically-change-the-value-of-a-color-resource-obtained-from-api-response) is the solution that may you looking for. – Mehul Solanki May 27 '19 at 12:57
  • Ok, thank you all. @Mehul Solanki thats not the answer i was looking for, but you are right! – JonasPTFL May 28 '19 at 18:35