开发者

ListPreference with a max number of selectable options

开发者 https://www.devze.com 2022-12-16 02:12 出处:网络
I want to have an element in my preference menu that does the following: Show a list of options. Many are selectable

I want to have an element in my preference menu that does the following:

  • Show a list of options.
  • Many are selectable
  • Maximum amount of options t开发者_Go百科o be chosen 2.

Possibilities I thought of:

  1. Doing a separated PreferenceScreen and showing options as checkBoxes, but I don't know where to place the logic of max 2 options.
  2. Extending DialogPreference and doing it by hand.

What's the best way?


Extending DialogPreference would get you the closest in terms of look-and-feel; the Preference classes are fairly unflexible and un-extendable in my experience.

I can't remember too much about PreferenceScreen, but I imagine it's similar.

In an app I worked on, we ended up using separate activities, launched via Intent from a Preference item onClick. This allowed us to easily develop preference screens that require validation logic a bit more complex than the usual.


You can put the logic of maximum two options in a OnSharedPreferenceChangeListener.

So you just listen to all the preferences as they change and update them if an invalid combination is selected.

So your code would be something like the following:

public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,String key) {
    //Code to calcuate how many are selected
    int code = numberSelected();

    if (count > 2) {
        sharedPreferences.edit().putBoolean(key,false).commit();
        Toast.makeText(this,"Can't select more than two!",Toast.LENGTH_LONG).show();
    }
}

If you create your own PreferenceActivity that implements OnSharedPreferenceChangeListener you can enable the listener to be listening only when required doing something like this:

@Override
protected void onResume() {
super.onResume();
    //Register the listener
    getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}

@Override
protected void onPause() {
    super.onPause();
    // Unregister the listener
    getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消