android setting default preferences from java
as the title above has said, is there any way to set default value of a preference from java code ?开发者_StackOverflow中文版
if it is done from the xml side, it should be android:defaultValue.
But, how to do it from the java side ??
THX for help
Unfortunately, the default value specified in the preferences XML only applies when using a PreferenceActivity
and its UI. However, if you take a look at the SharedPreferences
object, all of the get
methods allow you to specify a default value to retrieve when the preference does not have a value yet. Now, you can combine both the preferences XML and Java default values using constants in the xml files.
For example, declare a <string>
constant in a resource XML, then you can use it as the default value in the XML like so defaultValue="@string/myDefaultValue"
. Then, in your java code you can do:
sharedPrefs.getString("stringPreference", getString(R.string.myDefaultValue));
精彩评论