I have an app and I want to change ColorPrimary of app when user select color in settings? How I can do that?
Asked
Active
Viewed 198 times
0
-
You should save the setting to SharedPreferences, when display view, load the value from SharedPreferences. And when user select color, you can notify the app that the value was changed by [LocalBroadcastManager](http://stackoverflow.com/questions/8802157/how-to-use-localbroadcastmanager) or [EventBus](https://github.com/greenrobot/EventBus) – maphongba008 Sep 11 '16 at 13:53
-
@maphongba008 ok, but how to change color? – Олег Медведев Sep 11 '16 at 13:58
-
If you still can't solve your problem, I can give you an example code – maphongba008 Sep 11 '16 at 14:09
-
Themes are immutable. To achieve this, you can use `getWindow().setNavigationBarColor()` & `getWindow().setStatusBarColor()` in your `Activity` to change the colors. – Prasad Pawar Sep 11 '16 at 15:47
1 Answers
0
When the color is selected in Setting call this method
void onBackgroundColor(String color){
switch(color){
case "red":
sSavePreferences(getApplicationContext(), "color", "blue");
setBackground(color);
break;
case "blue":
sSavePreferences(getApplicationContext(), "color", "blue");
setBackground(color);
break;
case "green":
sSavePreferences(getApplicationContext(), "color", "blue");
setBackground(color);
break;
default:break;
}
}
void setBackground(String color){
//code to change background color
}
And this is method to save your setting using SharedPreferences
public static void sSavePreferences(Context context, String key, String value) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
And OnCreate of Activity you can load previous color by using this method
setBackground(sLoadSavedPreferencesString(getApplicationContext(), "color"));
For loading color:
public static String sLoadSavedPreferencesString(Context context, String key) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
String value = sharedPreferences.getString(key, "No Name Found");
return value;
}

Ngima Sherpa
- 1,397
- 1
- 13
- 34
-
Ok, but what if i want to change ColorPrimary, instead changing background color? – Олег Медведев Sep 11 '16 at 15:07