Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Create EditText on Runtime

Tags:

java

android

view

I'm trying to create a view where the user can click a "plus" button, and have additional EditTexts be created. The goal is to have a base of 2 EditTexts, and each time the user clicks the button, add another 2 EditTexts.

How can I do this? I can add EditTexts from Java, but I can't figure out how to add and handle a list of them dynamically.

I was hoping to take however many pairs of EditTexts, and push it into a key/value HashMap or something.

Any ideas of how to do this? Thanks!

like image 401
K. Barresi Avatar asked Jan 30 '26 10:01

K. Barresi


2 Answers

public class MyActivity extends Activity {

private LinearLayout main;
private int id = 0;
private List<EditText> editTexts = new ArrayList<EditText>();

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    main = new LinearLayout(this);
    main.setOrientation(LinearLayout.VERTICAL);

    Button addButton = new Button(this);
    addButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            addEditText();
        }
    });

    Button submit = new Button(this);
    submit.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            for (EditText editText : editTexts) {
                editText.getText().toString();
                // whatever u want to do with the strings
            }
        }
    });

    main.addView(addButton);
    main.addView(submit);
    setContentView(main);
}

private void addEditText() {
    LinearLayout editTextLayout = new LinearLayout(this);
    editTextLayout.setOrientation(LinearLayout.VERTICAL);
    main.addView(editTextLayout);

    EditText editText1 = new EditText(this);
    editText1.setId(id++);
    editTextLayout.addView(editText1);

    editTexts.add(editText1);

    EditText editText2 = new EditText(this);
    editText2.setId(id++);
    editTextLayout.addView(editText2);

    editTexts.add(editText2);

}
like image 136
eoghanm Avatar answered Feb 01 '26 23:02

eoghanm


Do it in a ListView. Then you can just add them to a ListAdapter.

And then use adapter.notifyDatasetChanged()

like image 22
AnAmuser Avatar answered Feb 02 '26 00:02

AnAmuser



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!