简体   繁体   中英

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM