在哪里存储Android偏好键?

当我创build首选项活动时,我定义了xml文件中的所有首选项。 每个首选项都有一个在这个XML中定义的键。 但是当我访问首选项时,我写道:

SharedPreferences appPreferences = PreferenceManager.getDefaultSharedPreferences(this); boolean foo_value = appPreferences.getBoolean("foo_key_defined_in_xml", false); 

有没有办法避免以硬编码方式引用“foo_key_defined_in_xml”? 也许有可能以R风格的方式引用它(不参考string)?

我发现可以将keys存储在strings.xml中,并像preferences.xml中的所有其他值android:key="@string/preference_enable"一样引用它们。

在代码中,您可以通过键入getString(R.string.preference_enable)来引用键

您可以将该string标记为不使用<xliff:g>标记进行翻译。 请参阅本地化清单

 <string name="preference_enable"><xliff:g id="preference_key">enable</xliff:g></string> 

你可以在“res / values”中使用“keys.xml”文件,但是应该放这样的东西,这样当你使用多种语言时你应该没有问题:

  <resources xmlns:tools="http://schemas.android.com/tools" tools:ignore="MissingTranslation"> <string name="key1">key1</string> <string name="key2">key2</string> ... </resources> 

然后你可以像xml中的普通string一样引用它:

 .... android:key="@string/key1" .... 

或者在你的java代码中,例如:

 SwitchPreference Pref1= (SwitchPreference) getPreferenceScreen().findPreference(getString(R.string.key1)); 

试试getString(R.string.key_defined_in_xml)

怎么样使用一个帮助类来隐藏getString() – 在每个活动或服务中实例化一次helper。 例如:

 class Pref { final String smsEnable_pref; final String interval_pref; final String sendTo_pref; final String customTemplate_pref; final String webUrl_pref; Pref(Resources res) { smsEnable_pref = res.getString(R.string.smsEnable_pref); interval_pref = res.getString(R.string.interval_pref); sendTo_pref = res.getString(R.string.sendTo_pref); customTemplate_pref = res.getString(R.string.customTemplate_pref); webUrl_pref = res.getString(R.string.webUrl_pref); } } 

据我所知没有更好的方式引用首选项键(除了可能使用静态最终string来存储string类)。

SDK文档中给出的示例与您在示例中给出的示例相同,