Recuperar valor de EditText en DialogFragment
Estoy pasando por la página de Google para desarrolladores de Android en Diálogos, específicamente en esta sección. Sin embargo, en lugar de crear el mensaje de DialogFragment mediante programación, hice un diseño layout_newpayperiod.xml
llamado layout_newpayperiod.xml
con los elementos siguientes:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Spinner android:id="@+id/spinner_payperiod" android:layout_width="fill_parent" android:layout_height="48dp" android:padding="8dp" android:entries="@array/pay_periods" /> <EditText android:id="@+id/edittext_savepercent" android:layout_width="fill_parent" android:layout_height="48dp" android:padding="8dp" android:inputType="number" android:hint="Percent to Save" /> <EditText android:id="@+id/edittext_payment" android:layout_width="fill_parent" android:layout_height="48dp" android:padding="8dp" android:inputType="numberDecimal" android:hint="Total Payment" /> </LinearLayout>
Cuando llamo al DialogFragment se muestra como normal, con el Spinner que tiene los valores apropiados. Rellené las entradas y presioné "Aceptar", pero cuando intento recuperar los valores de los campos Spinner y dos EditText, la aplicación se cierra con una NumberFormatException: Invalid double ""
. Tengo la sensación de que no estoy recuperando las vistas correctamente. ¿Puede alguien ayudarme a resolver esto por favor? ¡Gracias!
- Forma correcta de descartar DialogFragment mientras la aplicación está en segundo plano
- Llamar a DialogFragment del fragmento
- Android - ListFragment dentro DialogFragment (AlertDialog): Fragmento no tiene una vista
- Volver a llamar a un fragmento de un DialogFragment
- AlertDialog se descartó al volver a presionar
public class StartPayperiodDialogFragment extends DialogFragment { /* The activity that creates an instance of this dialog fragment must * implement this interface in order to receive event callbacks. * Each method passees the DialogFragment in case the host needs to query it. */ public interface StartPayperiodDialogListener{ public void onDialogPositiveClick(DialogFragment dialog); public void onDialogNegativeClick(DialogFragment dialog); } // Use this instance of the interface to deliver action events StartPayperiodDialogListener listener; // Override the Fragment.onAttach() method to instantiate the StartPayperiodDialogListener @Override public void onAttach(Activity activity){ super.onAttach(activity); // Verify that the host activity implements the callback interface try{ // Instantiate the NoticeDialogListener so we can send events to the host listener = (StartPayperiodDialogListener) activity; }catch(ClassCastException e){ // The activity doesn't implement the interface, throw exception throw new ClassCastException(activity.toString() + " must implement StartPayperiodDialogListener"); } } @Override public Dialog onCreateDialog(Bundle savedInstanceState){ // Use the Builder class for convenient dialog construction AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); View transactionLayout = View.inflate(getActivity(), R.layout.layout_newpayperiod, null); builder.setView(transactionLayout) .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Send the positive button event back to the calling activity listener.onDialogPositiveClick(StartPayperiodDialogFragment.this); } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Send the negative button event back to the calling activity listener.onDialogNegativeClick(StartPayperiodDialogFragment.this); } }); return builder.create(); }
}
En MainActivity.class, el método de devolución de llamada:
@Override public void onDialogPositiveClick(DialogFragment dialog) { // User pressed OK, so we need to grab the values from the // dialog's fields and apply them to the Views in the Main // Activity View transactionLayout = View.inflate(this, R.layout.layout_newpayperiod, null); // Start with the payment amount EditText paymentEt = (EditText) transactionLayout.findViewById(R.id.edittext_payment); TextView paymentTv = (TextView) findViewById(R.id.text_paycheck); paymentTv.setText(moneyFormat.format(Double.parseDouble(paymentEt.getText().toString()))); // Next, the percent to save EditText savingsEt = (EditText) transactionLayout.findViewById(R.id.edittext_savepercent); TextView savingsTv = (TextView) findViewById(R.id.text_savings); savingsTv.setText(savingsEt.getText().toString() + "%"); // Then, the pay period Spinner periodSp = (Spinner) transactionLayout.findViewById(R.id.spinner_payperiod); TextView periodTv = (TextView) findViewById(R.id.text_payperiod); periodTv.setText(periodSp.getSelectedItem().toString()); // Finally, let's update the daily allowance amount and clear // the adapter adapter.clear(); adapter.notifyDataSetChanged(); TextView allowanceTv = (TextView) findViewById(R.id.text_allowance); Double allowanceValue; switch(periodSp.getSelectedItemPosition()){ case(0): // Daily allowanceValue = Double.parseDouble(paymentTv.getText().toString()); break; case(1): // Weekly allowanceValue = Double.parseDouble(paymentTv.getText().toString()) / 7; break; case(2): // 2 Weeks allowanceValue = Double.parseDouble(paymentTv.getText().toString()) / 14; break; case(3): // 30 Days allowanceValue = Double.parseDouble(paymentTv.getText().toString()) / 30; break; default: // Debugging purposes only allowanceValue = 42.0; break; } allowanceTv.setText(Double.toString(allowanceValue)); }
- El título de Android DialogFragment no se muestra
- Android: FragmentTransaction ocultar no funciona para DialogFragment
- Actividad se ha filtrado ventana com.android.internal.policy.impl.PhoneWindow$DecorView@46029dd0
- DialogFragment no funciona con SOFT_INPUT_ADJUST_PAN
- GetLocationOnScreen devuelve la posición antigua después de la rotación
- ¿Debemos usar setTargetFragment ()? Pensé que los fragmentos no deberían comunicarse entre sí
- OnCancelListener no se llama en DialogFragment
- Iniciar un fragmento de diálogo en el botón de clic de un adaptador de base personalizado> getView
Prueba esto:
@Override public void onDialogPositiveClick(DialogFragment dialog) { // User pressed OK, so we need to grab the values from the // dialog's fields and apply them to the Views in the Main // Activity // Start with the payment amount Dialog dialogView = dialog.getDialog(); EditText paymentEt = (EditText) dialogView.findViewById(R.id.edittext_payment);
… etc. (Recupere cualquier otra vista desde el cuadro de diálogo consultando el cuadro de diálogo de la misma manera.)
Su código de inflación "infla" una nueva versión de esa vista. Desea acceder a la que se creó en el diálogo.
Creo que esta línea View transactionLayout = View.inflate(this, R.layout.layout_newpayperiod, null);
Ensucia todo Tal vez no es ensuciar, pero usted está recibiendo la dirección del diseño recién creado y asignarlo a la referencia transactionLayout
. Entonces usted está consiguiendo las vistas de esa disposición EditText paymentEt = (EditText) transactionLayout.findViewById(R.id.edittext_payment);
Que ciertamente no son iniciados. Tiene valor valor de cadena vacío -> "";
Creo que debe utilizar findViewById para obtener referencia a su EditText como lo hace con su TextView. Pero a medida que se encuentra en su MainActivity
cuyo diseño probablemente no es una vista primaria para su R.layout.layout_newpayperiod
, debe encontrar una manera de hacerlo correctamente.
Usted tiene su DialogFragment
como parámetro en este método de devolución de llamada onDialogPositiveClick
. Así que usted puede obtener su View
y el diseño que está buscando – que contiene su EditText
Lo siento por editar este post tantas veces.