AlertDialog with EditText in android

Android alert dialog is a window which prompt while the user is doing some action. Mostly the dialog will consist of two button named OK or CANCEL.  And a message which is decision making on something. Apart from that android is allowing to add some widget like EditText to alert dialog to get some values  from the user based on the requirement.In my previous tutorial Android AlertDialog Example ,am showing how to implement simple alert dialog. Here in this example Let us see how to simply add an EditText or any other widget to AlertDialog.

For Achieving this you need to dynamically create a LinearLayout which will contain your EditText using the following code.

LinearLayout ll_alert_layout = new LinearLayout(this);
ll_alert_layout.setOrientation(LinearLayout.VERTICAL);
final EditText ed_input = new EditText(this);
ll_alert_layout.addView(ed_input);

Now it is as simple as adding this layout to your AlertDialog using setView method. Following is the function which contains full AlertDialog code. Call this function on your action

public void CreateAlertDialog() {

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

    LinearLayout ll_alert_layout = new LinearLayout(this);
    ll_alert_layout.setOrientation(LinearLayout.VERTICAL);
    final EditText ed_input = new EditText(this);
    ll_alert_layout.addView(ed_input);

    alertbox.setTitle("Title");
    alertbox.setMessage("Enter your text");

    //setting linear layout to alert dialog

    alertbox.setView(ll_alert_layout);

    alertbox.setNegativeButton("CANCEL",
            new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface arg0, int arg1) {

            // will automatically dismiss the dialog and will do nothing

                }
            });


    alertbox.setPositiveButton("OK",
            new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface arg0, int arg1) {

                    String input_text = ed_input.getText().toString();

            // do your action with input string

                }
            });
    alertbox.show();
}

output

android-editexttext-in-alertdialog
android-editexttext-in-alertdialog
As like EditText you can create other widgets as well inside AlertDialog. 
For that just create the layout dynamically and set to alertdialog.

About the author

Hi guys, i am the author of codesfor. I am a B.Tech graduate currently working as an App developer. Apart from job i am a blogger and a freelancer.

Add a Comment

Your email address will not be published. Required fields are marked *