pix*_*xel 56 java android android-preferences
当我创建首选项活动时,我在xml文件中定义所有首选项.每个首选项都有一个在此xml中定义的键.但当我访问首选项时,我写道:
SharedPreferences appPreferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean foo_value = appPreferences.getBoolean("foo_key_defined_in_xml", false);
有没有办法避免以硬编码的方式引用"foo_key_defined_in_xml"?也许有可能以R风格的方式引用它(不是指字符串)?
pix*_*xel 71
我发现可以在strings.xml中存储密钥,并从preferences.xml中引用它们,就像所有其他值一样android:key="@string/preference_enable".
在代码中,您可以通过键入来引用密钥  getString(R.string.preference_enable)
您可以使用标记将字符串标记为不翻译<xliff:g>.请参阅本地化核对表
<string name="preference_enable"><xliff:g id="preference_key">enable</xliff:g></string>
小智 13
你可以在"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中的普通字符串一样引用它:
....
android:key="@string/key1"
....
或者在你的java代码中例如:
SwitchPreference Pref1= (SwitchPreference) getPreferenceScreen().findPreference(getString(R.string.key1));
在 strings.xml 中将键标记为不可翻译:
<string name="screw_spacing_key" translatable="false">Screw spacing</string>
<string name="screw_spacing_title">Screw spacing</string>
<string name="screw_spacing_summary">Set screw spacing</string>
用法:
<EditTextPreference
    android:key="@string/screw_spacing_key"
    android:title="@string/screw_spacing_title"
    android:summary="@string/screw_spacing_summary"/>
请参阅:配置不可翻译的行