問題描述
我已經根據 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 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()
方法,但這似乎有點棘手...我無法將 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();
}
這篇關于如何從 Android 中每個動態創建的 EditText 獲取數據?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!