开发者

Android: Preference default Value

开发者 https://www.devze.com 2023-02-11 01:18 出处:网络
I have 3 - 4 Activities. One of those is the main activity and a second one is a Preference Screen. I have a preference screen with different Preferenc开发者_如何学Pythones like ListPreference etc tha

I have 3 - 4 Activities. One of those is the main activity and a second one is a Preference Screen. I have a preference screen with different Preferenc开发者_如何学Pythones like ListPreference etc that have default values.

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:

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. If you want all the defaults specified in one place, you might need to call Preference.setDefaultValue() rather than setting it in the 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


Store the preferences using SharedPreferences, and load them in your MainActivity. SharedPreferences has get methods that you pass in a default value to return if the preference doesn't yet exist.

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


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. It initializes the preferences to the values stored in your XML file.

0

精彩评论

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

关注公众号