Josh Beckwith
Josh Beckwith

Reputation: 1540

Android: How to set button colors from settings

In my app I want to have a settings page, where you can set the color of the buttons in the app to green, blue, or red. Can I do this with SharedPreferences? If so, let's say I save the color to "BUTTON_COLOR" In my shared preferences. How can I recall the setting in my activities to set the button color? Thanks guys.

Upvotes: 1

Views: 331

Answers (2)

mrres1
mrres1

Reputation: 1155

The Android SDK provides the SharedPreferences class to set and get App preferences.

These preferences are for small amounts of data, and there are methods for the all the data types (including String).

The preferences are removed when the App is uninstalled. Or if the user goes to their device settings, finds the App and selects the "Clear Cache" button.

You can set preferences this way:

SharedPreferences get = getSharedPreferences("MyApp", Context.MODE_PRIVATE);
SharedPreferences.Editor set = get.edit();

set.putInt("BUTTON_COLOR", 0xFF000000);
set.commit(); // You must call the commit method to set any preferences that you've assigned.

And you can retrieve them this way:

get.getInt("BUTTON_COLOR", 0xFF000000); // A preference will never return null.  You set a default value as the second parameter.

Upvotes: 1

drewhannay
drewhannay

Reputation: 1020

Anywhere you create a button in the app, you're going to have to check what the value of the SharedPreference is and set the button color appropriately.

Saving the preference:

PreferenceManager.getDefaultSharedPreferences(activity).edit().putInt("COLOR",color);

Reading it out again (where the second parameter to getInt() is the default value for the color):

PreferenceManager.getDefaultSharedPreferences(activity).getInt("COLOR",Color.BLACK);

For more info, see: http://developer.android.com/reference/android/content/SharedPreferences.html

Upvotes: 2

Related Questions