Where to store Android preference keys?

When I create a preference activity, I define all the settings in the xml file. Each preference has a key defined in this xml. But when I get access to preference, I write:

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

Is there a way to avoid the foo_key_defined_in_xml link in a hard-coded way? Perhaps it is possible to refer to it in the style of R (not to refer to a string)?

+43
java android android-preferences
May 18 '10 at 12:18
source share
5 answers

I found that you can store keys in strings.xml and refer to them from preferences.xml , like all other android:key="@string/preference_enable" values android:key="@string/preference_enable" .

In code, you can access the key by typing getString(R.string.preference_enable)

You can mark a line that should not be translated using the <xliff:g> . See Localization Checklist

 <string name="preference_enable"><xliff:g id="preference_key">enable</xliff:g></string> 
+59
May 19 '10 at 9:10
source share

You can use the "keys.xml" files in "res / values", but you should put something like this, so you should not have a problem when using multiple languages:

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

Then you can refer to it as a regular string in xml:

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

or in your java code, for example:

 SwitchPreference Pref1= (SwitchPreference) getPreferenceScreen().findPreference(getString(R.string.key1)); 
+7
Mar 27 '16 at 3:54 on
source share

Try getString(R.string.key_defined_in_xml) .

+1
May 18 '10 at 12:37 a.m.
source share

How to use the helper class to hide getString () - create an instance of the helper once in each action or service. For example:

 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); } } 
+1
Feb 09 '11 at 10:38
source share

As far as I know, there is no better way to reference preference keys (other than using a static final string to store the string in the class).

the example specified in the SDK docs does the same as in your example,

0
May 18 '10 at 12:33
source share



All Articles