共享首选项切换不起作用

时间:2018-01-15 12:53:15

标签: android xml settings preferenceactivity android-sharedpreferences

我已经阅读了所有内容,但我认为我理解了它,但是我的代码中的某些东西并不起作用,我真的不确定原因,有人可以帮助我吗?我的设置活动有3个开关,我想将它们与3个共享首选项布尔值对齐,所以我的活动扩展了PreferenceActivity并实现了SharedPreferences.OnSharedPreferenceChangeListener我的开关在onCreate中初始化,然后我在我的活动中稍后重写onSharedPreferenceChanged

ujm = (SwitchPreference) findPreference(getString(R.string.ujmkey));
totaljobs = (SwitchPreference) findPreference(getString(R.string.totaljobskey));
indeed = (SwitchPreference) findPreference(getString(R.string.indeedkey));



@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
    if (key.equals("ujmkey")) {
        boolean ujmbool = sharedPreferences.getBoolean("ujmkey", false);
        //Do whatever you want here. This is an example.
        if (ujmbool) {
            ujm.setSummary("Enabled");
            ujm.setChecked(true);
        } else {
            ujm.setSummary("Disabled");
            ujm.setChecked(false);
        }
    }
    if (key.equals("totaljobskey")) {
        boolean totaljobsbool = sharedPreferences.getBoolean("totaljobskey", false);
        //Do whatever you want here. This is an example.
        if (totaljobsbool) {
            totaljobs.setSummary("Enabled");
            totaljobs.setChecked(true);
        } else {
            totaljobs.setSummary("Disabled");
            totaljobs.setChecked(true);
        }
    }
    if (key.equals("indeedkey")) {
        boolean indeedbool = sharedPreferences.getBoolean("indeedkey", false);
        //Do whatever you want here. This is an example.
        if (indeedbool) {
            indeed.setSummary("Enabled");
            indeed.setChecked(true);
        } else {
            indeed.setSummary("Disabled");
            indeed.setChecked(true);
        }
    }
}

此代码更新了第一个交换机摘要,但没有其他任何内容并没有更新任何共享首选项(我认为这是自动发生的)共享首选项键肯定是正确的,也许它的问题与我的xml生病包括在这里

<PreferenceScreen 
xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
    android:title="Inputs" >
<SwitchPreference
    android:title="@string/ujm"
    android:key="@string/ujmkey"/>
<SwitchPreference
    android:title="@string/totaljobs"
    android:key="@string/totaljobskey"/>
<SwitchPreference
    android:title="@string/indeed"
    android:key="@string/indeedkey"/>
</PreferenceCategory>

<PreferenceCategory
    android:title="Data" >

<Preference android:title="Delete"
    android:key="@string/pref_delete"
    android:summary="Deletes all saved data"/>

</PreferenceCategory>

<PreferenceCategory android:title="FAQ" >

    <Preference android:title="About"
    android:summary="About the app"
    android:key="about"/>

    <Preference
    android:title="Share"
    android:summary="Share the app with friends"
    android:key="share"/>

</PreferenceCategory>

0 个答案:

没有答案