简体   繁体   English

Android:首选项默认值

[英]Android: Preference default Value

I have 3 - 4 Activities. 我有3-4次活动。 One of those is the main activity and a second one is a Preference Screen. 其中一个是主要活动,第二个是偏好屏幕。 I have a preference screen with different Preferences like ListPreference etc that have default values. 我有一个首选项屏幕,其中包含不同的首选项,如ListPreference等,它们具有默认值。

How can i activate default Value of Settings when I start my project? 如何在启动项目时激活默认设置值?

By default, they activate only when I start the Settings Activity. 默认情况下,它们仅在我启动“设置活动”时激活。 Shortly: I need to use the default value in the main activity without calling the Settings Activity. 简而言之:我需要在不调用“设置活动”的情况下使用主活动中的默认值。

What I do is have a static method in my Preferences activity class, so it can be called from anywhere: 我所做的是在我的Preferences活动类中有一个静态方法,因此可以从任何地方调用它:

static public boolean getOrderByDate(Context context) {
    SharedPreferences prefs = 
            PreferenceManager.getDefaultSharedPreferences(context);
    return prefs.getBoolean("order_by_date", true);
}

Note that my default value (true) is specified here in the getBoolean() call. 请注意,我的默认值(true)在getBoolean()调用中指定。 If you want all the defaults specified in one place, you might need to call Preference.setDefaultValue() rather than setting it in the XML. 如果要在一个位置指定所有默认值,则可能需要调用Preference.setDefaultValue()而不是在XML中设置它。

There is a method for this. 有一种方法。 See the docs 查看文档

PreferenceManager.setDefaultValues(this, R.xml.advanced_preferences, false);

Call it at in the onCreate of your main activity. 在主要活动的onCreate中调用它。 It initializes the preferences to the values stored in your XML file. 它将首选项初始化为存储在XML文件中的值。

Just set it like that if you use Shared Preferences. 如果您使用共享首选项,只需设置它。

public static String PlayerName = "";
public static int CardsCount = 52;
public static int PlayersCount = 5;

Also implement LoadSettings() and SaveSettings() methods and it will work fine 还可以实现LoadSettings()和SaveSettings()方法,它可以正常工作

Store the preferences using SharedPreferences , and load them in your MainActivity. 使用SharedPreferences存储首选项,并将其加载到MainActivity中。 SharedPreferences has get methods that you pass in a default value to return if the preference doesn't yet exist. 如果首选项尚不存在,SharedPreferences将获取您传递的默认值的方法。

Update: Code Example 更新:代码示例

In your Main Activity 在您的主要活动中

// get the shared preferences for your package context
SharedPreferences sharedPreferences = PreferencesManager.getSharedPreferences(this);
// get the boolean preference with a default value of false
boolean somePref = sharedPrefernces.getBoolean("somePref", false);
// get the string preference with a default value of "default"
String someOtherPref = sharedPreferences.getStirng("someOtherPref", "default");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM