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)?
Android Shared Preferences Overview Android stores Shared Preferences settings as XML file in shared_prefs folder under DATA/data/{application package} directory. The DATA folder can be obtained by calling Environment.
The preference option doesn't exist anymore. You will need to right click the res -> new -> Android resource file and choose the resource type as xml in the dropdown. Then you will manually need to add the layout for preference xml.
Preferences in Android are used to keep track of application and user preferences. In any application, there are default preferences that can accessed through the PreferenceManager instance and its related method getDefaultSharedPreferences(Context)
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>
You could use a "keys.xml" files in "res/values", but should put something like this, this way you should dont have problem when you are 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 could reference it like a normal string in xml:
.... android:key="@string/key1" ....
or in your java code for example:
SwitchPreference Pref1= (SwitchPreference) getPreferenceScreen().findPreference(getString(R.string.key1));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With