除从定制preference值 [英] Save value from custom Preference

查看:117
本文介绍了除从定制preference值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个新的preference直接从复选框preference 延伸。在这个类中我添加了一个简单的新布尔值。我现在的问题是我怎么也得保存这个新的价值。如果用户点击一个正常的复选框preference 的值是全自动存储在preferences。我想,出现这种情况也与我的新的价值。为此,我想我一定要覆盖的方法,但我不知道其中哪些。另外我有两个布尔现在的值(检查和我自己),所以我必须建立一个逻辑或像这样用整数,因为有四种不同的可能性有两个布尔值。因此,如何有效地存储我的两个值和这方法我都覆盖了呢?

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?

推荐答案

您应该使用共享preference ,您存储值和密钥对。例如关键的是色preference和值是绿色。它即使你关闭应用程序不会被删除。

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.

//设置共享preference

//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

//删除键 - 值对如果没有必要再

SharedPreferences.Editor editor = sharedPreferencesFDefault.edit();
editor.remove("studentNameColor");
editor.commit();

//删除每个键 - 值对内defaultShared preference

//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.

这篇关于除从定制preference值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆