2010-03-25 12 views
8

Uso la preferencia de lista en mi aplicación Android y obtengo los valores clave y todo está bien y funciona bien (ahora que me han ayudado) PERO - cuando mis menús de preferencia emergente, solo contienen un botón cancelar.Usar la preferencia de la lista y obtener la clave funciona pero no el botón Aceptar

Digamos que el usuario elige entre rojo, azul y verde. Cuando el diálogo de preferencia de lista aparece por primera vez, el cuadro de diálogo solo muestra un botón de cancelar. Debido a eso, el diálogo desaparece tan pronto como el usuario selecciona su elección. Me gustaría que cuando el usuario elija su configuración, vea que el botón de radio se resalte y luego continúe y haga clic en el botón Aceptar ... pero no tengo un botón de autorización y no puedo entender por qué. Cualquier ayuda sería increíble ... al

Respuesta

6

Puede clonar y volver a implementar ListPreference para que funcione de la manera que desee, por lo que creará su propia clase personalizada Preference.

Sin embargo, ListPreference está configurado para usar solo un botón negativo ("Cancelar"). Como el código fuente dice:

/* 
    * The typical interaction for list-based dialogs is to have 
    * click-on-an-item dismiss the dialog instead of the user having to 
    * press 'Ok'. 
    */ 
6

que haya hecho lo sugerido y aplicado mi propia ListPreference basado en el código fuente de Android la respuesta anterior. Debajo está mi implementación que agrega el botón OK.

myPreferenceList.java

import android.app.AlertDialog.Builder; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.content.DialogInterface.OnClickListener; 
import android.preference.ListPreference; 
import android.util.AttributeSet; 


public class myPreferenceList extends ListPreference implements OnClickListener{ 

    private int mClickedDialogEntryIndex; 

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


    } 

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

    private int getValueIndex() { 
     return findIndexOfValue(this.getValue() +""); 
    } 


    @Override 
    protected void onPrepareDialogBuilder(Builder builder) { 
     super.onPrepareDialogBuilder(builder); 

     mClickedDialogEntryIndex = getValueIndex(); 
     builder.setSingleChoiceItems(this.getEntries(), mClickedDialogEntryIndex, new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int which) { 
       mClickedDialogEntryIndex = which; 

      } 
     }); 

     System.out.println(getEntry() + " " + this.getEntries()[0]); 
     builder.setPositiveButton("OK", this); 
    } 

    public void onClick (DialogInterface dialog, int which) 
    { 
     this.setValue(this.getEntryValues()[mClickedDialogEntryIndex]+""); 
    } 

} 

continuación, puede utilizar la clase en su preference.xml de la siguiente manera:

<com.yourApplicationName.myPreferenceList 
      android:key="yourKey" 
      android:entries="@array/yourEntries" 
      android:entryValues="@array/yourValues" 
      android:title="@string/yourTitle" /> 
+0

Para ser más específicos: implementa DialogInterface.OnClickListener – southerton

4

El código por techi50 es correcta, pero no funciona para 'botón de cancelación '. Éstos son algunos modificación:

protected void onPrepareDialogBuilder(Builder builder) { 
    super.onPrepareDialogBuilder(builder); 

    prevDialogEntryIndex = getValueIndex();  // add this 
    mClickedDialogEntryIndex = getValueIndex(); 
    builder.setSingleChoiceItems(this.getEntries(), mClickedDialogEntryIndex, new DialogInterface.OnClickListener() { 
    public void onClick(DialogInterface dialog, int which) { 
      mClickedDialogEntryIndex = which; 

     } 
    }); 

    builder.setPositiveButton("OK", this); 
} 

public void onClick (DialogInterface dialog, int which) 
{ 
// when u click Cancel: which = -2; 
// when u click  OK: which = -1; 

    if(which == -2){ 
     this.setValue(this.getEntryValues()[prevDialogEntryIndex]+""); 
    } 
    else { 
     this.setValue(this.getEntryValues()[mClickedDialogEntryIndex]+""); 
    } 
} 
1

La solución propuesta por Techi50 y Ajinkya funciona bien. Sin embargo, si también tiene el OnPreferenceChangeListener, no se activará.

yourListPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { 
        @Override 
        public boolean onPreferenceChange(Preference preference, Object o) { 

         //Won't get there 

         preference.setSummary(o.toString()); 
         return true; 
        } 
       }); 

Para solucionar este problema, es necesario invocar la función callChangeListener() en el botón Aceptar clic, así:

public void onClick (DialogInterface dialog, int which) { 
     if(which == -2) { 
      this.setValue(this.getEntryValues()[mClickedDialogEntryIndexPrev]+""); 
     } 
     else { 
      String value = this.getEntryValues()[mClickedDialogEntryIndex] + ""; 
      this.setValue(value); 
      callChangeListener(value); 
     } 
    } 
Cuestiones relacionadas