简体   繁体   中英

Android: Create EditText on Runtime

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!

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

}

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

And then use adapter.notifyDatasetChanged()

May be I am not clear but Instead of adding Individual edit text you can add as Group View like Linear layout here you can use any flag values to add dynamic name conversions also.

That view you can update into List View like inflating rows in the List View....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM