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
- Cómo implementar correctamente onRestoreInstanceState () para una subclase DialogPreference?
- Cómo cambiar el color del divisor PreferenceCategory en PreferenceScreen
- ¿Cuál es la diferencia de AppCompatPreferenceActivity y SettingActivity?
- Cómo crear una preferencia que acepte sólo valores enteros
- ¿Cómo obtener las preferencias del sistema Android?
- Preferencia personalizada, targetSdkVersion = "11": falta el sangrado?
- ¿Cuál es la diferencia entre getDefaultSharedPreferences () y getPreferences ()?
- TimePicker en PreferenceScreen
- Añadir ActionBar a una preferenciaActividad
- Cómo eliminar la preferencia compartida mientras se desinstala la aplicación en android
- Preferencias de Android parecen estar ignorando setDefaultValue
- Android - No hay método getEditText en EditTextPreference con Preference Support Library
- ¿Cómo llamo a un PreferenceFragment específico de una PreferenceActivity?
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); } }
- Ocultar vista previa de la clave del teclado de Android
- No se puede escribir editText en el emulador de Mac