Where to store Android preference keys?

pixel picture pixel · May 18, 2010 · Viewed 15.8k times · Source

When I create preference activity I define all preferences in xml file. Every preference has a key defined in this xml. But when I access preference I write:

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

Is there any way to avoid referencing "foo_key_defined_in_xml" in hard-coded way? Maybe there is a possibility to reference it in R style way (not to refer to string)?

Answer

pixel picture pixel · May 19, 2010

I've found that it's possible to store keys in strings.xml and refer to them from preferences.xml just like all other values android:key="@string/preference_enable".

In code you can refer to key by typing getString(R.string.preference_enable)

You can mark the string to not be translated using a <xliff:g> tag. See Localization Checklist

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