2013-04-08 92 views
-1

這段代碼是否爲完全是是否正確?獲取所有子編輯框的值

myRLayout = (RelativeLayout) findViewById(R.id.rel_layout); 

for(int i = 0; i < myRLayout.getChildCount(); i++) { 
View v = myRLayout.getChildAt(i); 
if(v instanceof EditText) { 
     TextView res = (TextView) findViewById(R.id.result_text); 
     String str1 = ((EditText) findViewById(R.id.edittext_1)).getText().toString(); 
     String str2 = ((EditText) findViewById(R.id.edittext_2)).getText().toString(); 
     res.setText(str1+str2); 
    } 
} 

爲什麼我問?對於每次迭代,只有一個EditText可以一次或全部一起使用?

回答

1

使用v子實例從所有EditText中獲取值,並使用TextView.append顯示TextView中的值。試試它:

TextView res = (TextView) findViewById(R.id.result_text); 
res.setText(""); //<< clear textview here 
for(int i = 0; i < myRLayout.getChildCount(); i++) { 
View v = myRLayout.getChildAt(i); 
if(v instanceof EditText) { 
     String str1 = v.getText().toString(); //<< get text from ith EditText 
     res.append(str1); // append value to result_text TextView 
    } 
} 
+0

好的。但我需要這些字符串轉換爲浮點數,並與他們做一些計算... – user2230842 2013-04-08 17:30:00

+0

@ user2230842:如果你想對EditText值進行計算,然後首先在ArrayList中的所有值,然後使用ArrayList將字符串轉換爲浮點數並在顯示之前執行計算它的TextView – 2013-04-08 17:43:41