Skip to content Skip to sidebar Skip to footer

Android Colors In Sharedpreferences

In my application is settings_activity where people can change some colors (icons, text etc). I want to put colors in sharedpreferences, created class: public class AppData { s

Solution 1:

If you are going to use the color enumeration, I would just use an int to store it. (See below for data type of ints)

http://developer.android.com/reference/android/graphics/Color.html

However, if you are going to use the hexadecimal value, then I would store it as a string. When you load your app, check the shared preferences and load the string and if the option does not exist load a default color.

object.setColor(sharedPreferences.getString("COLOR", "#FFFFFF"));.

Solution 2:

if the user give you hex string ( as you answer to NoChinDeluxe) you should store it in string in your sharePref and then parse it with :

publicstaticintparseColor(String colorString)

I always do my Prefs like this:

privatestatic final StringKEY_COLOR_1 = "color 1";

privatestaticPrefs instance;

publicstaticPrefswith(Context ctx) {
    if (instance == null) {
        instance = newPrefs();
    }
    instance.ctx = ctx.getApplicationContext();
    return instance;
}

privateContext ctx;

privatePrefs() {
}

publicSharedPreferencesgetPrefs() {
    returnPreferenceManager.getDefaultSharedPreferences(ctx);
}
publicStringgetColor1() {
        returngetPrefs().getStrings(KEY_COLOR_1, "");
    }

    publicvoidsetColor1(String color) {
        getPrefs().edit().putStrings(KEY_COLOR_1, color).apply();
    }

and then you can get your color with:

Pref.with(this).getColor1();

Post a Comment for "Android Colors In Sharedpreferences"