Cuadro de diálogo de entrada de texto Android

Resuelto Luke Taylor asked hace 54 años • 8 respuestas

Cuando un usuario hace clic en Buttonen mi aplicación (que está impresa en un archivo SurfaceView), me gustaría Dialogque aparezca un texto y me gustaría almacenar el resultado en un archivo String. Me gustaría que el texto Dialogse superponga a la pantalla actual. ¿Cómo puedo hacer esto?

Luke Taylor avatar Jan 01 '70 08:01 Luke Taylor
Aceptado

Parece una buena oportunidad para utilizar AlertDialog .

Por más básico que parezca, Android no tiene un cuadro de diálogo integrado para hacer esto (hasta donde yo sé). Afortunadamente, es sólo un poco de trabajo extra además de crear un AlertDialog estándar. Simplemente necesita crear un EditText para que el usuario ingrese datos y configurarlo como la vista de AlertDialog. Puede personalizar el tipo de entrada permitida usando setInputType , si es necesario.

Si puede utilizar una variable miembro, simplemente puede establecer la variable en el valor de EditText y persistirá después de que se cierre el cuadro de diálogo. Si no puede usar una variable miembro, es posible que necesite usar un oyente para enviar el valor de la cadena al lugar correcto. (Puedo editar y elaborar más si esto es lo que necesitas).

Dentro de tu clase:

private String m_Text = "";

Dentro del OnClickListener de tu botón (o en una función llamada desde allí):

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Title");

// Set up the input
final EditText input = new EditText(this);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
builder.setView(input);

// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { 
    @Override
    public void onClick(DialogInterface dialog, int which) {
        m_Text = input.getText().toString();
    }
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        dialog.cancel();
    }
});

builder.show();
Aaron avatar Jun 05 '2012 20:06 Aaron

Agregaré a la respuesta de @Aaron un enfoque que le brinda la oportunidad de diseñar mejor el cuadro de diálogo. Aquí hay un ejemplo ajustado:

AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Title");
// I'm using fragment here so I'm using getView() to provide ViewGroup
// but you can provide here any other instance of ViewGroup from your Fragment / Activity
View viewInflated = LayoutInflater.from(getContext()).inflate(R.layout.text_inpu_password, (ViewGroup) getView(), false);
// Set up the input
final EditText input = (EditText) viewInflated.findViewById(R.id.input);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
builder.setView(viewInflated);

// Set up the buttons
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        dialog.dismiss();
        m_Text = input.getText().toString();
    }   
}); 
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        dialog.cancel();
    }   
}); 

builder.show();

Este es el diseño de ejemplo utilizado para crear el cuadro de diálogo Editar texto:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="@dimen/content_padding_normal">

    <android.support.design.widget.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <AutoCompleteTextView
            android:id="@+id/input"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/hint_password"
            android:imeOptions="actionDone"
            android:inputType="textPassword" />

    </android.support.design.widget.TextInputLayout>
</FrameLayout>

El resultado final:

Ejemplo de diálogo Editar texto

Michal avatar Feb 13 '2016 17:02 Michal

¿ Qué tal este EJEMPLO ? Parece sencillo.

final EditText txtUrl = new EditText(this);

// Set the default text to a link of the Queen
txtUrl.setHint("http://www.librarising.com/astrology/celebs/images2/QR/queenelizabethii.jpg");

new AlertDialog.Builder(this)
  .setTitle("Moustachify Link")
  .setMessage("Paste in the link of an image to moustachify!")
  .setView(txtUrl)
  .setPositiveButton("Moustachify", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
      String url = txtUrl.getText().toString();
      moustachify(null, url);
    }
  })
  .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
    }
  })
  .show(); 
bhekman avatar Jun 05 '2012 20:06 bhekman