2010-08-10 2 views
7

J'essaie de créer une boîte de dialogue de préférence qui permet à l'utilisateur de sélectionner plus d'un élément dans la liste. Actuellement, il vous permet uniquement de sélectionner un élément. Y a-t-il un moyen facile de faire ceci? J'ai regardé partout sur internet et je n'ai pas vu un moyen pour le moment. Toute aide est appréciée!Un moyen facile de faire le choix multiple ListPreference dans Android?

Répondre

0

Les préférences sont des valeurs uniques par définition. Si vous souhaitez implémenter un choix multiple ListPreference vous devrez peut-être sous-classer cette classe ou android.preference.Preference et créer votre propre implémentation.

Vous pouvez également appeler une activité à partir d'un simple écran de préférences et gérer vous-même tout.

Vous pouvez stocker les valeurs dans une préférence Chaîne avec un séparateur ou, mieux encore, différentes préférences booléennes.

10

Voici tout le code dont vous avez besoin!

http://blog.350nice.com/wp/wp-content/uploads/2009/07/listpreferencemultiselect.java

public class ListPreferenceMultiSelect extends ListPreference { 
    //Need to make sure the SEPARATOR is unique and weird enough that it doesn't match one of the entries. 
    //Not using any fancy symbols because this is interpreted as a regex for splitting strings. 
    private static final String SEPARATOR = "OV=I=XseparatorX=I=VO"; 

    private boolean[] mClickedDialogEntryIndices; 

    public ListPreferenceMultiSelect(Context context, AttributeSet attrs) { 
     super(context, attrs); 

     mClickedDialogEntryIndices = new boolean[getEntries().length]; 
    } 

    @Override 
    public void setEntries(CharSequence[] entries) { 
     super.setEntries(entries); 
     mClickedDialogEntryIndices = new boolean[entries.length]; 
    } 

    public ListPreferenceMultiSelect(Context context) { 
     this(context, null); 
    } 

    @Override 
    protected void onPrepareDialogBuilder(Builder builder) { 
     CharSequence[] entries = getEntries(); 
     CharSequence[] entryValues = getEntryValues(); 

     if (entries == null || entryValues == null || entries.length != entryValues.length) { 
      throw new IllegalStateException(
        "ListPreference requires an entries array and an entryValues array which are both the same length"); 
     } 

     restoreCheckedEntries(); 
     builder.setMultiChoiceItems(entries, mClickedDialogEntryIndices, 
       new DialogInterface.OnMultiChoiceClickListener() { 
        public void onClick(DialogInterface dialog, int which, boolean val) { 
         mClickedDialogEntryIndices[which] = val; 
        } 
     }); 
    } 

    public static String[] parseStoredValue(CharSequence val) { 
     if ("".equals(val)) 
      return null; 
     else 
      return ((String)val).split(SEPARATOR); 
    } 

    private void restoreCheckedEntries() { 
     CharSequence[] entryValues = getEntryValues(); 

     String[] vals = parseStoredValue(getValue()); 
     if (vals != null) { 
      for (int j=0; j<vals.length; j++) { 
       String val = vals[j].trim(); 
       for (int i=0; i<entryValues.length; i++) { 
        CharSequence entry = entryValues[i]; 
        if (entry.equals(val)) { 
         mClickedDialogEntryIndices[i] = true; 
         break; 
        } 
       } 
      } 
     } 
    } 

    @Override 
    protected void onDialogClosed(boolean positiveResult) { 
//  super.onDialogClosed(positiveResult); 

     CharSequence[] entryValues = getEntryValues(); 
     if (positiveResult && entryValues != null) { 
      StringBuffer value = new StringBuffer(); 
      for (int i=0; i<entryValues.length; i++) { 
       if (mClickedDialogEntryIndices[i]) { 
        value.append(entryValues[i]).append(SEPARATOR); 
       } 
      } 

      if (callChangeListener(value)) { 
       String val = value.toString(); 
       if (val.length() > 0) 
        val = val.substring(0, val.length()-SEPARATOR.length()); 
       setValue(val); 
      } 
     } 
    } 
} 
0

Merci pour le poste, il m'a beaucoup aidé. J'ai apporté quelques modifications à la classe pour permettre aux utilisateurs de mettre à jour le résumé affiché dans les préférences avec les valeurs sélectionnées. De cette manière, l'utilisateur peut voir ses choix sans ouvrir le Spinner.

Voici les méthodes ajoutées:

// Fills the Entry Values List 
@Override 
public void setEntryValues(CharSequence[] entryValues) { 
    super.setEntryValues(entryValues); 
    restoreCheckedEntries(); 
} 

// Updates the Summary 
@Override 
public void setSummary(CharSequence entries) { 
    String s = ""; 
    for (int x = 0; x < getEntryValues().length; x++) 
     if (mClickedDialogEntryIndices[x]) 
      s += (s.equals("") ? "" : ", ") + getEntries()[x]; 
    super.setSummary(s); 
} 

La méthode setSummary doit être convoquée dans le SettingsActivity.java ici:

private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener 
= new Preference.OnPreferenceChangeListener() { 

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

     if (preference instanceof ListPreferenceMultiSelect) {    
      ListPreferenceMultiSelect listPreference = 
       (ListPreferenceMultiSelect) preference; 
      listPreference.setSummary("");  
    } 

    return true; 
    } 
}; 

La méthode setEntryValues ​​peuvent être appelés avec setEntries.

Cela a fonctionné pour moi! Compatible avec Android 2.2 ou plus récent.

Questions connexes