Cómo agregar dos campos de texto de edición en un cuadro de diálogo de alerta

Estoy tratando de usar un cuadro de diálogo de alerta para pedir un nombre de usuario y una contraseña en android. He encontrado este código aquí:

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: He podido configurar el diseño adecuado, pero recibir un error cuando intento acceder al campo de texto. ¿Cuál es el problema aquí?

Las demostraciones de API en el SDK de Android tienen un ejemplo que hace exactamente eso.

Está bajo DIALOG_TEXT_ENTRY . Tienen un diseño, lo inflar con un LayoutInflater , y utilizarlo como la vista.

EDIT: Lo que había vinculado a en mi respuesta original es rancio. Aquí hay un espejo .

Compruebe este código en el cuadro de alerta que ha editado textview cuando haga clic en Aceptar que se muestra en la pantalla utilizando tostadas.

 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(); } 

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

  final EditText input1 = (EditText) textEntryView .findViewById(R.id.username); final EditText input2 = (EditText) textEntryView .findViewById(R.id.password); 
  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(); 
  /* 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(); 

Compruebe el código siguiente. Muestra 2 campos de edición de texto mediante programación sin ningún formato xml. Cambie 'this' a 'getActivity ()' si lo usa en un fragmento.

Lo complicado es que tenemos que configurar 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(); } 

Echa un vistazo a los documentos de AlertDialog. Como se indica, para agregar una vista personalizada a su cuadro de diálogo de alerta que necesita para encontrar el frameLayout y añadir su vista a que así:

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

Lo más probable es que desee crear un archivo xml de diseño para su vista e inflarlo:

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

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 API de Google, debe importar su jar (s) de demostración (s) en su proyecto, que probablemente no desea.

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 necesitas ajustarlo a tus necesidades. Vea aquí

  • ParseFacebookUtils logInWithReadPermissionsInBackground fecha no válida
  • Android: el inicio de sesión de Facebook provoca error de onResume sólo por primera vez
  • Android - Facebook SDK 3 - Cómo iniciar sesión mediante programación sin LoginButton
  • Android: ¿Puedo usar google ClientLogin para el registro de usuarios?
  • Facebook SDK en Android: invalidar u ocultar el diálogo de progreso cuando inicie sesión
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.