問題描述
我已經(jīng)根據(jù) Android 中的用戶輸入成功創(chuàng)建了 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.
現(xiàn)在我要做的是在用戶點(diǎn)擊按鈕時從動態(tài)創(chuàng)建的 EditText
中獲取值,然后將它們?nèi)看鎯υ?String 變量中.即來自 EditText 的具有 id '1' 的值應(yīng)保存在 String 類型的 str1 中,依此類推,具體取決于 EditText 的數(shù)量.
Now what I want to do is to get values from the dynamically created EditText
s 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()
方法,但這似乎有點(diǎn)棘手...我無法將 EditText 的每個值分配給一個字符串變量.當(dāng)我嘗試這樣做時,會發(fā)生 NullPointerException
,如果不是沒有顯示用戶輸入數(shù)據(jù)的情況,我會在 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);
}
我現(xiàn)在如何將每個 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
變量,所以當(dāng)循環(huán)結(jié)束時 ed
只指向您創(chuàng)建的最后一個 EditText 實(shí)例.
In every iteration you are rewriting the ed
variable, so when loop is finished ed
only points to the last EditText instance you created.
您應(yīng)該存儲對所有 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);
}
現(xiàn)在 allEds
列表保存對所有 EditTexts 的引用,因此您可以對其進(jìn)行迭代并獲取所有數(shù)據(jù).
Now allEds
list hold references to all EditTexts, so you can iterate it and get all the data.
更新:
根據(jù)要求:
String[] strings = new String[](allEds.size());
for(int i=0; i < allEds.size(); i++){
string[i] = allEds.get(i).getText().toString();
}
這篇關(guān)于如何從 Android 中每個動態(tài)創(chuàng)建的 EditText 獲取數(shù)據(jù)?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!