开发者

android setting default preferences from java

开发者 https://www.devze.com 2023-03-21 11:34 出处:网络
as the title above has said, is there any way to set default value of a preference from java code ?开发者_StackOverflow中文版

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));
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号