如何从 Android 中每个动态创建的 EditText 获取数据?

2022-01-14 00:00:00 string android java android-edittext

我已经根据 Android 中的用户输入成功创建了 EditText,并且我还使用 setId() 方法为它们分配了唯一 ID.

I have successfully created EditTexts depending on the user input in Android, and also I have assigned them unique ID's using setId() method.

现在我要做的是在用户点击按钮时从动态创建的 EditText 中获取值,然后将它们全部存储在 String 变量中.即来自 EditText 的具有 id '1' 的值应保存在 String 类型的 str1 中,依此类推,具体取决于 EditText 的数量.

Now what I want to do is to get values from the dynamically created EditTexts when the user tap a button, then store all of them in String variables. i.e. value from EditText having id '1' should be saved in str1 of type String, and so on depending on the number of EditTexts.

我正在使用 getid()gettext().toString() 方法,但这似乎有点棘手...我无法将 EditText 的每个值分配给一个字符串变量.当我尝试这样做时,会发生 NullPointerException,如果不是没有显示用户输入数据的情况,我会在 toast 中显示它.

I am using getid(), and gettext().toString() methods but it seems a bit tricky... I cannot assign each value of EditText to a String variable. When I try to do that a NullPointerException occurs, and if it is not the case where no user input data is shown, I display it in a toast.

这里,代码:

EditText ed;

for (int i = 0; i < count; i++) {   

        ed = new EditText(Activity2.this);
        ed.setBackgroundResource(R.color.blackOpacity);
        ed.setId(id);   
        ed.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));
        linear.addView(ed);

}

我现在如何将每个 EditText 的值传递给每个不同的字符串变量?如果有人可以帮助提供示例代码,那就太好了.

How do I now pass the value from each EditText to each different string variable? If some body could help with a sample code it would be nice.

推荐答案

在每次迭代中你都在重写 ed 变量,所以当循环结束时 ed 只指向您创建的最后一个 EditText 实例.

In every iteration you are rewriting the ed variable, so when loop is finished ed only points to the last EditText instance you created.

您应该存储对所有 EditTexts 的所有引用:

You should store all references to all EditTexts:

EditText ed;
List<EditText> allEds = new ArrayList<EditText>();

for (int i = 0; i < count; i++) {   

    ed = new EditText(Activity2.this);
    allEds.add(ed);
    ed.setBackgroundResource(R.color.blackOpacity);
    ed.setId(id);   
    ed.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
            LayoutParams.WRAP_CONTENT));
    linear.addView(ed);
}

现在 allEds 列表保存对所有 EditTexts 的引用,因此您可以对其进行迭代并获取所有数据.

Now allEds list hold references to all EditTexts, so you can iterate it and get all the data.

更新:

根据要求:

String[] strings = new String[](allEds.size());

for(int i=0; i < allEds.size(); i++){
    string[i] = allEds.get(i).getText().toString();
}

相关文章