本文介绍了Android:在运行时创建 EditText的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个视图,用户可以在其中单击加号"按钮,并创建其他 EditText.目标是以 2 个 EditText 为基础,每次用户单击按钮时,再添加 2 个 EditText.

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.

我该怎么做?我可以从 Java 添加 EditText,但我不知道如何动态添加和处理它们的列表.

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.

我希望采用多对 EditTexts,并将其推送到键/值 HashMap 或其他东西中.

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

}

这篇关于Android:在运行时创建 EditText的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 16:20