views:

299

answers:

2

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 to 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?

Thanks.

+2  A: 

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.

Christopher
This is what I did: * Extend from DialogPreference. * On onCreateDialogView I create a layout with different checkboxes. * My values are loaded in a String separated by a token. * Created a class that coverts from String to int[] and vice versa. ** This class uses a HashSet and has a maxSize.It's kind of a hack but it works :)Thanks Christopher.
Macarse
+1  A: 

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);
}
Dave Webb