How do you get the default value of an Android preference defined in XML? I don't want to repeat the definition of the default value in both the code and the preferences 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)
It's still possible to customise the appearance of a Preference item though. In your XML you have to declare the root element as android:id="@android:id/widget_frame , and then declare TextView as android:title and android:summary . You can then declare other elements you want to appear in the layout.
A SharedPreferences object points to a file containing key-value pairs and provides simple methods to read and write them. Each SharedPreferences file is managed by the framework and can be private or shared. This page shows you how to use the SharedPreferences APIs to store and retrieve simple values.
Programmatically: getPreferenceScreen(). findPreference("yourpref"). setEnabled(false);
You can define default value in resources (/values/bool.xml
):
<resources> <bool name="mypreference_default">true</bool> </resources>
Use the value in the preferences.xml
:
<CheckBoxPreference android:defaultValue="@bool/mypreference_default" android:key="mypreference" android:title="@string/mypreference_title" />
Then use in code:
SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(context); Boolean value = context.getResources().getBoolean(R.bool.mypreference_default); Boolean b = p.getBoolean("mypreference", value);
First you need to define default values in your preference XML file. Then you can populate preferences with default values in your main Activity by calling:
PreferenceManager.setDefaultValues(this, R.xml.preference, false);
When you need to retrieve a some preference just call:
int value = prefs.getInt("key", null);
Since your preferences are populated you won't get null
value.
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