Search code examples
androidandroid-edittextandroid-alertdialogbuilder

Android AlertDialog Builder multiple EditText


I am wanting to use Android AlertDialog.Builder to programatically structure the layout of a dialog. I have two EditText fields that I want to display, displayed vertically, one on top of another, but I can't get it to work. The following code just displays the second one, as if it is being displayed over the first one linearly instead of vertically.

final EditText inputOne = new EditText(MainActivity.this);
final EditText inputTwo = new EditText(MainActivity.this);

LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.WRAP_CONTENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT
                );

AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
inputOne.setLayoutParams(lp);
inputOne.setLayoutParams(lp);

alertDialog.setView(inputOne);
alertDialog.setView(inputTwo);

Solution

  • Take a parent Layout and add the the views and finally set the view to dialog like this way:

        LinearLayout parent = new LinearLayout(this);
    
        parent.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        parent.setOrientation(LinearLayout.VERTICAL);
    
        parent.addView(inputOne);
        parent.addView(inputTwo);
    
        alertDialog.setView(parent);