2010-08-06 13 views
52

Estoy tratando de usar un cuadro de diálogo de alerta para solicitar un nombre de usuario y una contraseña en android. He encontrado este código here:Cómo agregar dos campos de texto de edición en un cuadro de diálogo de alerta

if (token.equals("Not Found")) 
    { 
     LayoutInflater factory = LayoutInflater.from(this);    
     final View textEntryView = factory.inflate(R.layout.userpasslayout, null); 

     AlertDialog.Builder alert = new AlertDialog.Builder(this); 

     alert.setTitle("Please Login to Fogbugz"); 
     alert.setMessage("Enter your email and password"); 
     // Set an EditText view to get user input 
     alert.setView(textEntryView); 
     AlertDialog loginPrompt = alert.create(); 

     final EditText input1 = (EditText) loginPrompt.findViewById(R.id.username); 
     final EditText input2 = (EditText) loginPrompt.findViewById(R.id.password); 

     alert.setPositiveButton("Login", new DialogInterface.OnClickListener() { 
     public void onClick(DialogInterface dialog, int whichButton) { 
      input1.getText().toString(); **THIS CRASHES THE APPLICATION** 


     } 
     }); 

     alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int whichButton) { 
      // Canceled. 
      } 
     }); 

     alert.show(); 

    } 

EDIT: yo era capaz de configurar la disposición adecuada, pero recibirá un error cuando intento acceder al campo de texto. ¿Cuál es el problema aquí?

Respuesta

25

Las Demos API en el SDK de Android tienen un ejemplo que hace precisamente eso.

Está bajo DIALOG_TEXT_ENTRY. Tienen un diseño, lo inflan con un LayoutInflater y lo usan como la Vista.

EDITAR: Lo que había vinculado en mi respuesta original es obsoleto. Aquí hay un mirror.

+0

Esto funcionó, pero sigue recibiendo un error al intentar acceder a la EditarTexto. Edité mi respuesta, ¿hay algún problema porque los campos aún no están construidos? – mbauer14

+3

¿Qué es "el error"? – EboMike

+0

Este código de ejemplo ya no está presente en el sitio web o en las últimas muestras – conners

1

Eche un vistazo a AlertDialog docs. Como se indica, para agregar una vista personalizada a su diálogo de alerta que necesita para encontrar la FrameLayout y añadir su fin de que de este modo:

FrameLayout fl = (FrameLayout) findViewById(android.R.id.custom); 
fl.addView(myView, new LayoutParams(MATCH_PARENT, WRAP_CONTENT)); 

Lo más probable es que usted va a querer crear un archivo XML de diseño para su punto de vista, y inflarlo:

LayoutInflater inflater = getLayoutInflater(); 
View twoEdits = inflater.inflate(R.layout.my_layout, f1, false); 
19

Utilice estas líneas en el código, ya que el textEntryView es el padre de EditarTexto nombre de usuario y contraseña EditarTexto.

final EditText input1 = (EditText) textEntryView .findViewById(R.id.username); 
    final EditText input2 = (EditText) textEntryView .findViewById(R.id.password); 
+0

estado atascado en esto por tanto tiempo.Pensé que no me estaba inflando correctamente, pero resulta que estaba usando el padre equivocado. Gracias por su aporte Nandy! – Kitteh

62

Comprobar el código de cuadro de alerta tiene edición de Vista de Texto cuando se haga clic en Aceptar se muestra en pantalla mediante una tostada.

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    final AlertDialog.Builder alert = new AlertDialog.Builder(this); 
    final EditText input = new EditText(this); 
    alert.setView(input); 
    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { 
     public void onClick(DialogInterface dialog, int whichButton) { 
      String value = input.getText().toString().trim(); 
      Toast.makeText(getApplicationContext(), value, 
       Toast.LENGTH_SHORT).show(); 
     } 
    }); 

    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
     public void onClick(DialogInterface dialog, int whichButton) { 
      dialog.cancel(); 
     } 
    }); 
    alert.show();    
} 
+15

Quería dos campos EditText ... no uno – Dediqated

+0

Simplemente agregue otro con el nombre input2 y luego alert.setView (input2); – Nepster

+6

@Nepster - 'set' significa que la nueva vista (entrada2) anulará la vista anterior (entrada1). –

0

Encontré otro conjunto de ejemplos para personalizar un AlertDialog de un tipo llamado Mossila. Creo que son mejores que los ejemplos de Google. Para ver rápidamente las demostraciones de la API de Google, debe importar sus jar demo (s) a su proyecto, que probablemente no desee.

Pero el código de ejemplo de Mossila es totalmente autónomo. Se puede cortar y pegar directamente en su proyecto. ¡Simplemente funciona! Entonces solo necesita ajustarlo a sus necesidades. Consulte here

10
LayoutInflater factory = LayoutInflater.from(this); 
final View textEntryView = factory.inflate(R.layout.text_entry, null); 
//text_entry is an Layout XML file containing two text field to display in alert dialog 
final EditText input1 = (EditText) textEntryView.findViewById(R.id.EditText1); 
final EditText input2 = (EditText) textEntryView.findViewById(R.id.EditText2);    
input1.setText("DefaultValue", TextView.BufferType.EDITABLE); 
input2.setText("DefaultValue", TextView.BufferType.EDITABLE); 
final AlertDialog.Builder alert = new AlertDialog.Builder(this); 

alert.setIcon(R.drawable.icon) 
    .setTitle("Enter the Text:") 
    .setView(textEntryView) 
    .setPositiveButton("Save", 
     new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int whichButton) { 
        Log.i("AlertDialog","TextEntry 1 Entered "+input1.getText().toString()); 
        Log.i("AlertDialog","TextEntry 2 Entered "+input2.getText().toString()); 
        /* User clicked OK so do some stuff */ 
      } 
     }) 
    .setNegativeButton("Cancel", 
     new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, 
        int whichButton) { 
      } 
     }); 
alert.show(); 
2

Compruebe el siguiente código. Muestra 2 campos de texto de edición mediante programación sin ningún diseño xml. Cambia 'this' a 'getActivity()' si lo usas en un fragmento.

Lo complicado es que tenemos que establecer el tipo de entrada del segundo campo de texto después de crear el cuadro de diálogo de alerta, de lo contrario, el segundo campo de texto muestra textos en lugar de puntos.

public void showInput() { 
     OnFocusChangeListener onFocusChangeListener = new OnFocusChangeListener() { 
      @Override 
      public void onFocusChange(final View v, boolean hasFocus) { 
       if (hasFocus) { 
        // Must use message queue to show keyboard 
        v.post(new Runnable() { 
         @Override 
         public void run() { 
          InputMethodManager inputMethodManager= (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
          inputMethodManager.showSoftInput(v, 0); 
         } 
        }); 
       } 
      } 
     }; 

     final EditText editTextName = new EditText(this); 
     editTextName.setHint("Name"); 
     editTextName.setFocusable(true); 
     editTextName.setClickable(true); 
     editTextName.setFocusableInTouchMode(true); 
     editTextName.setSelectAllOnFocus(true); 
     editTextName.setSingleLine(true); 
     editTextName.setImeOptions(EditorInfo.IME_ACTION_NEXT); 
     editTextName.setOnFocusChangeListener(onFocusChangeListener); 

     final EditText editTextPassword = new EditText(this); 
     editTextPassword.setHint("Password"); 
     editTextPassword.setFocusable(true); 
     editTextPassword.setClickable(true); 
     editTextPassword.setFocusableInTouchMode(true); 
     editTextPassword.setSelectAllOnFocus(true); 
     editTextPassword.setSingleLine(true); 
     editTextPassword.setImeOptions(EditorInfo.IME_ACTION_DONE); 
     editTextPassword.setOnFocusChangeListener(onFocusChangeListener); 

     LinearLayout linearLayout = new LinearLayout(this); 
     linearLayout.setOrientation(LinearLayout.VERTICAL); 
     linearLayout.addView(editTextName); 
     linearLayout.addView(editTextPassword); 

     DialogInterface.OnClickListener alertDialogClickListener = new DialogInterface.OnClickListener() { 
      @Override 
      public void onClick(DialogInterface dialog, int which) { 
       switch (which){ 
       case DialogInterface.BUTTON_POSITIVE: 
        // Done button clicked 
        break; 
       case DialogInterface.BUTTON_NEGATIVE: 
        // Cancel button clicked 
        break; 
       } 
      } 
     }; 
     final AlertDialog alertDialog = (new AlertDialog.Builder(this)).setMessage("Please enter name and password") 
       .setView(linearLayout) 
       .setPositiveButton("Done", alertDialogClickListener) 
       .setNegativeButton("Cancel", alertDialogClickListener) 
       .create(); 

     editTextName.setOnEditorActionListener(new OnEditorActionListener() { 
      @Override 
      public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { 
       editTextPassword.requestFocus(); // Press Return to focus next one 
       return false; 
      } 
     }); 
     editTextPassword.setOnEditorActionListener(new OnEditorActionListener() { 
      @Override 
      public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { 
       // Press Return to invoke positive button on alertDialog. 
       alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).performClick(); 
       return false; 
      } 
     }); 

     // Must set password mode after creating alert dialog. 
     editTextPassword.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD); 
     editTextPassword.setTransformationMethod(PasswordTransformationMethod.getInstance()); 
     alertDialog.show(); 
    } 
7
   /* Didn't test it but this should work "out of the box" */ 

       AlertDialog.Builder builder = new AlertDialog.Builder(this); 
       //you should edit this to fit your needs 
       builder.setTitle("Double Edit Text"); 

       final EditText one = new EditText(this); 
       from.setHint("one");//optional 
       final EditText two = new EditText(this); 
       to.setHint("two");//optional 

       //in my example i use TYPE_CLASS_NUMBER for input only numbers 
       from.setInputType(InputType.TYPE_CLASS_NUMBER); 
       to.setInputType(InputType.TYPE_CLASS_NUMBER); 

       LinearLayout lay = new LinearLayout(this); 
       lay.setOrientation(LinearLayout.VERTICAL); 
       lay.addView(one); 
       lay.addView(two); 
       builder.setView(lay); 

       // Set up the buttons 
       builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int whichButton) { 
         //get the two inputs 
         int i = Integer.parseInt(one.getText().toString()); 
         int j = Integer.parseInt(two.getText().toString()); 
        } 
       }); 

       builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int whichButton) { 
         dialog.cancel(); 
       } 
       }); 
       builder.show(); 
Cuestiones relacionadas