Save value from custom Preference

2019-03-06 04:22发布

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条回答
We Are One
2楼-- · 2019-03-06 04:35

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.

查看更多
登录 后发表回答