问题
I have created a new preference which directly extends from CheckboxPreference
. In this class I added a simple new boolean
value. My question now is how I have to store this new value. If a user clicks a normal CheckboxPreference
the value is stored automaticly in the preferences. I want that this happens also with my new value. For this I think I have to overwrite a method but I do not know which of them. Also I have two boolean
values now (checked and my own) so I have to build a logic or something like this with integers because there are four different possibilities with two booleans. So how can I store my two values efficiently and which method do I have to overwrite for this?
回答1:
You should use SharedPreference
,which you store value and key pairs. For example key is "colorPreference" and value is "green". It doesn't get deleted even if you close app.
//Setting shared preference
public static SharedPreferences sharedPreferencesFDefault;
sharedPreferencesFDefault = PreferenceManager.getDefaultSharedPreferences(this);
//Adding something you want
SharedPreferences.Editor editor = sharedPreferencesFDefault.edit();
editor.putInt("studentNameColor", 2); // studentNameColor=2 for example
editor.commit();
//Getting value you have stored
int color = sharedPreferencesFDefault.getInt("studentNameColor", -1); // gets 2, if this key is not found, returns -1
//Deleting key-value
pair if no need anymore
SharedPreferences.Editor editor = sharedPreferencesFDefault.edit();
editor.remove("studentNameColor");
editor.commit();
//Delete every key-value
pair inside defaultSharedPreference
sharedPreferencesFDefault.edit().clear().commit();
Also you can use apply()
instead of commit()
which does operations asynchronously in background.
来源:https://stackoverflow.com/questions/29513056/save-value-from-custom-preference