Utilizar listpreference y obtener la clave funciona, pero no hay botón ok

Estoy utilizando listpreference en mi aplicación android y obtener mis valores clave y todo está bien y funciona bien (ahora que ustedes me han ayudado) PERO – cuando mis menús listpreference popup, sólo contienen un botón de cancelar.

Digamos que el usuario está eligiendo entre rojo, azul y verde. Cuando aparece el cuadro de diálogo de preferencia de listas, el cuadro de diálogo sólo muestra un botón de cancelación. Debido a eso, el diálogo desaparece tan pronto como el usuario selecciona su elección. Me gustaría que cuando el usuario escoge su configuración, vean el botón de radio se resalta y luego seguir adelante y haga clic en el botón ok … pero no tengo un botón de ok y no puedo entender por qué. Cualquier ayuda sería genial … al

Puede clonar y ListPreference a ListPreference para que funcione de la manera que desee, haciendo su propia clase de Preference personalizada como resultado.

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

  /* * 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'. */ 

He hecho lo que la respuesta anterior sugirió e implementé mi propia ListPreference basado en el código fuente de Android. A continuación se muestra mi implementación que agrega el botón Aceptar.

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]+""); } } 

A continuación, puede utilizar la clase en su preferencia.xml como sigue:

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

El código de techi50 es correcto, pero no funciona para 'cancelar el botón'. He aquí algunas modificaciones:

 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]+""); } } 

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

  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 esto, necesita invocar la función callChangeListener () en el botón OK, haga clic en, como esto:

  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); } } 
  • Android: onSharedPreferenceChanged no cambia un resumen de PreferenceScreen
  • ¿Cómo obtener todas las claves de SharedPreferences mediante programación en Android?
  • Vista personalizada en Preferencias de diálogo
  • Después de cambiar una preferencia (una configuración), el texto que muestra la configuración no se actualiza
  • Cambiar el color del selector de una preferencia
  • ¿La mejor práctica para llevar el material a Preferencias usando AppCompat?
  • Android: cómo abrir un cuadro de diálogo ListPreference desde fuera de PreferenceActivity / PreferenceFragment?
  • Weird SwitchPrefererence en el comportamiento de restablecimiento automático PreferenciaCategoría
  • Uso de findviewbyid en preferenciaactividad
  • Cambiar la fuente PreferenceFragment a través de fuentes de activos
  • Compatibilidad para SwitchPreference (pre ICS)?
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.