Reputation: 195
I am having an app with 3 screens currently.
1 is a main screen with 6 buttons and 2 of which buttons have an intent to go to the other 2 screens.
1 of those screens is Themes. It has 6 layouts whose color of BG changes to white when clicked. It is fine but i need to save this preference of the user out of 6 and have it further used in my tic-tac-toe images..... all 6 themes will change tic-tac-toe pieces...thats my plan (*Mainly imageview imageresource change...thats all).
I want that whenever person closes that Themes Screen with selecting ... suppose say 2nd one...whenever he opens back the screen or app, it should show the 2nd one selected...which user can change...and therefore change the value.
I tried sharedPreferences but didnt worked. Can anyone plz help me a bit? Moreover how to change imageView resource based on which theme selected? Use SharedPreferences get() for that?
Do answer if you can help. It will be greatly appreciated. Thanx in advance
Upvotes: 0
Views: 171
Reputation: 16068
I recently wrote an example for SharedPreferences
:
private static final String GLOBAL_PREFERENCES = "a.nice.identifier.for.your.preferences.goes.here";
public static void savePreferences(@NonNull Context context, String key, int value) {
SharedPreferences sharedPreferences = context.getSharedPreferences(GLOBAL_PREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.apply();
}
public static int loadPreferences(@NonNull Context context, String key, int defaultValue) {
SharedPreferences sharedPreferences = context.getSharedPreferences(GLOBAL_PREFERENCES, Context.MODE_PRIVATE);
return sharedPreferences.getInt(key, defaultValue);
}
This is an example for saving and loading an integer from SharedPreferences
.
These methods (and static final member variable) would be placed into a helper class called Utils
for the examples below:
In your example, when the user changes the theme (and wants to save that) you can call Utils.savePreferences(context, "theme", 1);
.
When the user returns to the App, you can use int theme = Utils.loadPreferences(context, "theme", 0);
to return their selected theme (or 0 for default).
Upvotes: 3