【问题标题】:PreferenceActivity with two SharedPreferences具有两个 SharedPreferences 的 PreferenceActivity
【发布时间】:2015-10-10 13:58:02
【问题描述】:

如何创建一个可以将值保存在两个不同的共享首选项中的首选项屏幕?

例如,在我的 PreferenceActivity 中,我的第一个首选项是 CheckBoxPreference。复选框的状态保存在“user_86_Prefs”sharedPreferences中,第二个首选项是ListPreference,选中项的状态保存在“devicePrefs”sharedPreference中。

在我的 PreferenceFragment 中我只能这样做

getPreferenceManager().setSharedPreferencesName("user_86_Prefs");

实际上,名为“user_86_Prefs”的sharedPreference是特定于连接在应用程序上的用户,而“devicePrefs”是特定于设备的。

我是否应该创建另一个扩展 PreferenceFragment 的类,并将特定于设备的首选项放入其中?如果是,我怎样才能在同一个 Activity 中拥有我的两个preferenceFragments?

谢谢

【问题讨论】:

    标签: android sharedpreferences


    【解决方案1】:

    一种方法是创建一个类来处理所有偏好。

    public class MySharedPreferences{
    
        private static final String USER_PREF = "user_shared_pref";
        private static final String DEVICE_PREF = "device_shared_pref";
    
        private static SharedPreferences getSharedPreferences(Context ctx){
            return PreferenceManager.getDefaultSharedPreferences(ctx);
        }
    
        public static void setUserPref(Context ctx,String user_pref){
            Editor editor = getSharedPreferences(ctx).edit();
            editor.putString(USER_PREF,user_pref);
            editor.apply();
        }
    
        public static String getUserPref(Context ctx){
            return getSharedPreferences(ctx).getString(USER_PREF,"");
        }
    }
    

    您的设备偏好也一样!你只需要做类似的事情来从其他类/活动/片段访问它:

    MySharedPreferences.setUserPref(this /* or whatever your context is*/,yourValue);
    

    【讨论】:

    • 多个用户可以连接到智能手机,我对每个用户都有一个偏好:user_86_Prefs、user_87_Prefs、user_42_Prefs、user_24_Prefs 等。例如 user_86_Prefs 不是字符串,它是一个包含字符串的 sharedPreference/ int/... 所以我需要为设备本身创建另一个共享首选项,它收集与智能手机相关的首选项。
    猜你喜欢
    • 1970-01-01
    • 2011-12-04
    • 2012-09-04
    • 2011-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多