Cómo hacer un cuadro de texto de edición en un diálogo

Estoy intentando hacer un cuadro de texto de edición en un cuadro de diálogo para ingresar una contraseña. y cuando lo hago, no puedo hacerlo. Soy un principiante en eso. Por favor, ayúdame en esto.

public class MainActivity extends Activity { Button create, show, setting; //String pass="admin";String password; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); create = (Button)findViewById(R.id.amcreate); setting = (Button)findViewById(R.id.amsetting); show = (Button)findViewById(R.id.amshow); //input = (EditText)findViewById(R.id.this); setting.setVisibility(View.INVISIBLE); create.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent myIntent1 = new Intent(view.getContext(), Create.class); startActivityForResult(myIntent1, 0); } }); show.setOnClickListener(new View.OnClickListener() { //@SuppressWarnings("deprecation") public void onClick(final View view) { // Creating alert Dialog with one Button AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this); //AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create(); // Setting Dialog Title alertDialog.setTitle("PASSWORD"); // Setting Dialog Message alertDialog.setMessage("Enter Password"); **final EditText input = new EditText(this);** //alertDialog.setView(input); // Setting Icon to Dialog alertDialog.setIcon(R.drawable.key); // Setting Positive "Yes" Button alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int which) { // Write your code here to execute after dialog Toast.makeText(getApplicationContext(),"Password Matched", Toast.LENGTH_SHORT).show(); Intent myIntent1 = new Intent(view.getContext(), Show.class); startActivityForResult(myIntent1, 0); } }); // Setting Negative "NO" Button alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // Write your code here to execute after dialog dialog.cancel(); } }); // closed // Showing Alert Message alertDialog.show(); } }); 

Imagen

enter image description here

Quiero llegar como

enter image description here

  AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this); alertDialog.setTitle("PASSWORD"); alertDialog.setMessage("Enter Password"); final EditText input = new EditText(MainActivity.this); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT); input.setLayoutParams(lp); alertDialog.setView(input); alertDialog.setIcon(R.drawable.key); alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { password = input.getText().toString(); if (password.compareTo("") == 0) { if (pass.equals(password)) { Toast.makeText(getApplicationContext(), "Password Matched", Toast.LENGTH_SHORT).show(); Intent myIntent1 = new Intent(view.getContext(), Show.class); startActivityForResult(myIntent1, 0); } else { Toast.makeText(getApplicationContext(), "Wrong Password!", Toast.LENGTH_SHORT).show(); } } } }); alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); alertDialog.show(); } }); 

Usar el contexto de Activtiy

Reemplace esto

  final EditText input = new EditText(this); 

Por

  final EditText input = new EditText(MainActivity.this); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT); input.setLayoutParams(lp); alertDialog.setView(input); // uncomment this line 

Sé que es demasiado tarde para responder a esta pregunta, pero para otros que están buscando algo similar a esto aquí hay un código simple de una alerta con un texto de edición

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

o

 new AlertDialog.Builder(mContext, R.style.MyCustomDialogTheme); 

si quieres cambiar el tema del diálogo.

 final EditText edittext = new EditText(ActivityContext); alert.setMessage("Enter Your Message"); alert.setTitle("Enter Your Title"); alert.setView(edittext); alert.setPositiveButton("Yes Option", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { //What ever you want to do with the value Editable YouEditTextValue = edittext.getText(); //OR String YouEditTextValue = edittext.getText().toString(); } }); alert.setNegativeButton("No Option", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // what ever you want to do with No option. } }); alert.show(); 

Versión simplificada

 final EditText taskEditText = new EditText(this); AlertDialog dialog = new AlertDialog.Builder(this) .setTitle("Add a new task") .setMessage("What do you want to do next?") .setView(taskEditText) .setPositiveButton("Add", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String task = String.valueOf(taskEditText.getText()); SQLiteDatabase db = mHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(TaskContract.TaskEntry.COL_TASK_TITLE, task); db.insertWithOnConflict(TaskContract.TaskEntry.TABLE, null, values, SQLiteDatabase.CONFLICT_REPLACE); db.close(); updateUI(); } }) .setNegativeButton("Cancel", null) .create(); dialog.show(); return true; 

Pruebe el siguiente código:

 alert.setTitle(R.string.WtsOnYourMind); final EditText input = new EditText(context); input.setHeight(100); input.setWidth(340); input.setGravity(Gravity.LEFT); input.setImeOptions(EditorInfo.IME_ACTION_DONE); alert.setView(input); 

El más simple de todos sería.

  • Crea un archivo de diseño xml para el diálogo. Agregue la vista que desee, como EditText, ListView, Spinner, etc.

    Inflar esta vista y configurar esto en AlertDialog

Comencemos primero con el archivo Layout.

     

 final View view = layoutInflater.inflate(R.layout.xml_file_created_above, null); AlertDialog alertDialog = new AlertDialog.Builder(ct).create(); alertDialog.setTitle("Your Title Here"); alertDialog.setIcon("Icon id here"); alertDialog.setCancelable(false); Constant.alertDialog.setMessage("Your Message Here"); final EditText etComments = (EditText) view.findViewById(R.id.etComments); alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { alertDialog.dismiss() } }); alertDialog.setView(view); alertDialog.show(); 

También puede crear un cuadro de diálogo de alerta personalizado creando un archivo xml.

dialoglayout.xml

       

El código de Java:

 @Override//to popup alert dialog public void onClick(View arg0) { // TODO Auto-generated method stub showDialog(DIALOG_LOGIN); }); @Override protected Dialog onCreateDialog(int id) { AlertDialog dialogDetails = null; switch (id) { case DIALOG_LOGIN: LayoutInflater inflater = LayoutInflater.from(this); View dialogview = inflater.inflate(R.layout.dialoglayout, null); AlertDialog.Builder dialogbuilder = new AlertDialog.Builder(this); dialogbuilder.setTitle("Title"); dialogbuilder.setView(dialogview); dialogDetails = dialogbuilder.create(); break; } return dialogDetails; } @Override protected void onPrepareDialog(int id, Dialog dialog) { switch (id) { case DIALOG_LOGIN: final AlertDialog alertDialog = (AlertDialog) dialog; Button loginbutton = (Button) alertDialog .findViewById(R.id.btn_login); Button cancelbutton = (Button) alertDialog .findViewById(R.id.btn_cancel); userName = (EditText) alertDialog .findViewById(R.id.dialog_txt_name); loginbutton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String name = userName.getText().toString(); Toast.makeText(Activity.this, name,Toast.LENGTH_SHORT).show(); }); cancelbutton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { alertDialog.dismiss(); } }); break; } } 

El margen de configuración en los parámetros de diseño no funcionará en Alertdialog. tiene que establecer el relleno en el diseño principal y luego agregar el texto de edición en ese diseño.

Este es mi código de trabajo de kotlin …

 val alert = AlertDialog.Builder(context!!) val edittext = EditText(context!!) edittext.hint = "Enter Name" edittext.maxLines = 1 val layout = FrameLayout(context!!) //set padding in parent layout layout.setPaddingRelative(45,15,45,0) alert.setTitle(title) layout.addView(edittext) alert.setView(layout) alert.setPositiveButton(getString(R.string.label_save), DialogInterface.OnClickListener { dialog, which -> run { val qName = edittext.text.toString() Utility.hideKeyboard(context!!, dialogView!!) } }) alert.setNegativeButton(getString(R.string.label_cancel), DialogInterface.OnClickListener { dialog, which -> run { dismiss() } }) alert.show()