MultiSelectListPreference获取已检查值?

时间:2018-08-02 22:48:15

标签: java android listpreference multiselectlistpreference

嗨,我想做一个简单的新闻阅读器应用。在共享的首选项中,用户可以选择他可以看到的新闻部分。直到Point添加MultiSelectListPreference并检索值。但不幸的是,它会检索所有值,而不仅是已检查的值。

这是我的代码:

<MultiSelectListPreference
            android:id="@+id/multiple_choice"
            android:dialogTitle="@string/section_news_label"
            android:entries="@array/news_sections"
            android:entryValues="@array/section_values"
            android:key="section_news_key"
            android:summary="@string/section_hint"
            android:defaultValue="@array/default_array"
            />

public class SettingsActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);
    }

    public static class NewsPreferenceFragment extends PreferenceFragment
            implements Preference.OnPreferenceChangeListener {

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.settings_main);

            Preference newsToShow = findPreference(getString(R.string.settings_news_show_key));
            bindPreferenceSummaryToValue(newsToShow);
        }

        @Override
        public boolean onPreferenceChange(Preference preference, Object value) {
            String stringValue = value.toString();
            preference.setSummary(stringValue);
            return true;
        }

        private void bindPreferenceSummaryToValue(Preference preference) {
            preference.setOnPreferenceChangeListener(this);
            SharedPreferences preferences =
                    PreferenceManager.getDefaultSharedPreferences(preference.getContext());
            String preferenceString = preferences.getString(preference.getKey(), "");
            onPreferenceChange(preference, preferenceString);
        }
    }
}

SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);


        Set<String> entries = sharedPrefs.getStringSet("section_news_key", null);
         if(entries == null){
             Log.v("!!!!!!!!!", "No entries");
         }else {
             Log.v("!!!!!!!!!", entries.toString());
         }

知道我在做什么错吗?

1 个答案:

答案 0 :(得分:1)

感谢我建立了运作良好的Solition。 需要使用HashSet。

//Get entries from news sections and store in Set
        Set<String> entries = sharedPrefs.getStringSet("section_news_key", new HashSet<String>());