代码之家  ›  专栏  ›  技术社区  ›  Donal Rafferty

Android复选框首选项默认值

  •  18
  • Donal Rafferty  · 技术社区  · 14 年前

    我有以下XML代码用于 CheckBoxPreference :

    <CheckBoxPreference
        android:key="pref_boot_startup"
        android:title="Auto start"
        android:defaultValue="true" />
    

    但是当我在代码中检索首选项时,值是 false .

    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    boolean autoStart = sharedPreferences.getBoolean("pref_boot_startup", true);
    

    我的 autoStart 变量返回 .

    有什么特别的原因吗?是否缺少将默认值设置为的步骤? true ?

    3 回复  |  直到 11 年前
        1
  •  35
  •   creativehandle    11 年前

        @Override
        protected void onCreate()
        {
            PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
            boolean autoStart = sharedPreferences.getBoolean("pref_boot_startup", true);
    
         {...}
        }
    
        3
  •  3
  •   walkarounder    13 年前
        // These two lines are working around an android bug:
        // http://code.google.com/p/android/issues/detail?id=6641
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        prefs.edit().putBoolean(REFRESH_COUNTER_PREF, prefs.getBoolean(REFRESH_COUNTER_PREF, true)).commit();
    
    推荐文章