我有3 - 4項活動。其中一個是主要活動,第二個是首選屏幕。我有一個首選項屏幕,其中包含具有默認值的不同首選項,如ListPreference等。Android:首選項默認值
當我開始我的項目時,如何激活設置的默認值?
默認情況下,它們僅在啓動設置活動時激活。很快:我需要在主要活動中使用默認值,而無需調用設置活動。
我有3 - 4項活動。其中一個是主要活動,第二個是首選屏幕。我有一個首選項屏幕,其中包含具有默認值的不同首選項,如ListPreference等。Android:首選項默認值
當我開始我的項目時,如何激活設置的默認值?
默認情況下,它們僅在啓動設置活動時激活。很快:我需要在主要活動中使用默認值,而無需調用設置活動。
我要做的就是在我的偏好活動類的靜態方法,所以它可以在任何地方被稱爲:
static public boolean getOrderByDate(Context context) {
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(context);
return prefs.getBoolean("order_by_date", true);
}
請注意,我的默認值(true)是在getBoolean()調用中指定的。如果您希望在一個地方指定所有默認值,則可能需要調用Preference.setDefaultValue(),而不是在XML中進行設置。
只要使用Shared Preferences就可以設置它。
public static String PlayerName = "";
public static int CardsCount = 52;
public static int PlayersCount = 5;
還實現LoadSettings()和SaveSettings()方法,它會正常工作
商店使用SharedPreferences喜好,並在MainActivity加載它們。如果首選項尚不存在,則SharedPreferences獲得您傳入的方法,並返回默認值以返回。
更新:代碼示例
在您的主要活動
// 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");
有一個這樣的方法。看到您的主要活動的onCreate
the docs
PreferenceManager.setDefaultValues(this, R.xml.advanced_preferences, false);
調用它。它將首選項初始化爲存儲在XML文件中的值。
你在做什麼「在主要活動中加載它們」? – Jim 2011-02-16 14:21:16