How to make a edittext box in a dialog

315,371

Solution 1

Use Activtiy Context

Replace this

  final EditText input = new EditText(this);

By

  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

Solution 2

I know its too late to answer this question but for others who are searching for some thing similar to this here is a simple code of an alertbox with an edittext

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

or

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

if you want to change the theme of the dialog.

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

Solution 3

Simplest of all would be.

  • Create xml layout file for dialog . Add whatever view you want like EditText , ListView , Spinner etc.

    Inflate this view and set this to AlertDialog

Lets start with Layout file first.

<?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:gravity="center_horizontal"
    android:orientation="vertical">

  
    <EditText
        android:id="@+id/etComments"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="top"
        android:hint="Enter comments(Optional)"
        android:inputType="textMultiLine"
        android:lines="8"
        android:maxLines="3"
        android:minLines="6"
        android:scrollbars="vertical" />

</LinearLayout>

final View view = layoutInflater.inflate(R.layout.xml_file_created_above, null);
AlertDialog alertDialog = new AlertDialog.Builder(requireContext()).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();

Solution 4

Simplified version

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;

Solution 5

Try below code:

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);
Share:
315,371

Related videos on Youtube

Abb
Author by

Abb

Presently I am working for an MNC at Hyderabad as a Developer in ASP.NET, C#, AngularJS, HTML, JQuery, Javascript. I have worked on Android, Blackberry Apps Development(QHTML), Java. At home I like to play with my Pet dog (Rott).

Updated on July 08, 2022

Comments

  • Abb
    Abb almost 2 years

    I am trying to make a edittext box in a dialog box for entering a password. and when I am doing I am not able to do. I am a beginner in it. Please help me in this.

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

    Image

    enter image description here

    I want to get as

    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();
     }
    
     });
    
  • Abb
    Abb over 10 years
    public void onClick(DialogInterface dialog, int which) { // Write your code here to execute after dialog dialog.cancel();
  • Raghunandan
    Raghunandan over 10 years
    @Abhishek wher is your initialization. Like Dialog dialog = new Dialog(MainActivity.this). I think you copied your code from else where i guess
  • Abb
    Abb over 10 years
    Sir, to be very true. I am a beginner.I just do research and then develop or implement. i basically understand some concepts.
  • Abb
    Abb over 10 years
    sir dialog is being given as a dialoginterface. when any one clicks on NO button it will get closed. should i use dialog.dismiss() ?
  • Raghunandan
    Raghunandan over 10 years
    @Abhishek sorry my confusion it thought you had custom dialog . public void onClick(DialogInterface dialog its the dialoginterface. using that is not a problem you click the negative button to dismiss the alertdialog.
  • Abb
    Abb over 10 years
    Thanks for editing.. i was frustated with some user behaviour. they just vote down. otherwise i would have gain 20+
  • Raghunandan
    Raghunandan over 10 years
    @Abhishek you are welcome glad to help but don't post those in question as it is irrelevant.
  • Abb
    Abb over 10 years
    sir what can i do if i want to display a message on empty textbox or wrong password entered. i want to display it in the dialog box insted in toast. can i do?
  • Raghunandan
    Raghunandan over 10 years
    @Abhishek display a toast message or set error for edittext. stackoverflow.com/questions/7747268/…
  • Abb
    Abb over 10 years
    cant i display in the dialog only? toast is easy to do.but the toast gets display at the bottom only . can toast be displayed at the centre of screen?
  • Raghunandan
    Raghunandan over 10 years
    @Abhishek you can use custom toast or set error to edittext. check the link posted in the above comment
  • Abb
    Abb over 10 years
    Toast toast = Toast.makeText(MainActivity.this,"Please Enter Password!", Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); this worked for me to get the toast in centre.
  • Lucifer
    Lucifer almost 10 years
    Hi Raghu, If I want to put left margin & right margin to this edittext box then what should I write ? I tried many answers, to set margin programmatically, but nothing worked :(
  • Raju
    Raju over 7 years
    this is what i needed but how can i use this in fragment its showing error
  • cerbin
    cerbin over 6 years
    Where should I place this code? When i tried this in the method, and final field EditText placed on top of the class, it crashes.
  • Syeda Zunaira
    Syeda Zunaira over 6 years
    what is the crash ?
  • adamcantcook
    adamcantcook over 6 years
    What a hero you are.
  • Brian Reinhold
    Brian Reinhold about 6 years
    Mine crashes too. It states that the edittext is null.
  • Brian Reinhold
    Brian Reinhold about 6 years
    I crash. I found the reason I crashed was I missed the 'view' on the findViewById. Now I just need to know how to handle a check box so I can show or hide the password WHILE the dialog is still alive. Tried the multi item approach but it added its own check box in addition to the one in my layout!
  • Ghanshyam Nayma
    Ghanshyam Nayma about 6 years
    How to give margin to this EditText ?
  • selvakumar
    selvakumar over 5 years
    Thanks saved my day
  • Jan Bergström
    Jan Bergström over 5 years
    Good suggestion of the asked topic, but a style comment is needed. Android is not Windows, and there is no need for a cancel button like it is a must in Win32, there is the OS "Back" button that serves as Cancel/No. So my suggestion is skipping the negative button on a password request dialog, and the positive button should not be "Yes" but should be "OK" (and get it localized by using android.R.string.ok). See more in my answer on the stackoverflow.com/questions/11459827/… topic.
  • Jan Bergström
    Jan Bergström over 5 years
    The edit field should also be a one liner (edittext.setSingleLine();) in a password request (because it is) and that makes pressing enter on an attached physical (BT) keyboard (or a Chromebook) making the focus jump to the next item, the positive button. meaning that after entering the text, pushing enter twice the dialogue is positively ended.
  • Jan Bergström
    Jan Bergström over 5 years
    Good suggestion of the asked topic, but a style comment is needed. Android is not Windows, and there is no need for a cancel button like it is a must in Win32, there is the OS "Back" button that serves as Cancel/No. So my suggestion is skipping the negative button on a password request dialog, and the positive button should not be "Yes" but should be "OK" (and get it localized by using android.R.string.ok). See more in my answer on the stackoverflow.com/questions/11459827/… topic.
  • Jan Bergström
    Jan Bergström over 5 years
    The edit field should also be a one liner (edittext.setSingleLine();) in a password request (because it is) and that makes pressing enter on an attached physical (BT) keyboard (or a Chromebook) making the focus jump to the next item, the positive button. meaning that after entering the text, pushing enter twice the dialogue is positively ended.
  • SMBiggs
    SMBiggs over 5 years
    Ah! The key is the call alert.setView()! And note that you can do this from a DialogBuilder as well.
  • Wesley Abbenhuis
    Wesley Abbenhuis about 5 years
    @GhanshyamNayma it is not a margin but a padding might be enough: edittext.setPadding(30, 20, 30, 20)
  • 林果皞
    林果皞 about 5 years
    How to change editText line color with this method ?
  • Vahag Chakhoyan
    Vahag Chakhoyan almost 5 years
    setView() requires API level 21
  • xaif
    xaif over 4 years
    how to give margin instead of matchParent in edit text ?
  • baskInEminence
    baskInEminence about 3 years
    Thank you! An answer that handles margin usage!