2013-01-22 23 views
0

我一直在想出如何將多個EditText值加在一起並將輸出顯示爲一個TextView如何在一個文本視圖中顯示多個編輯文本字段的內容?

更具體地:

我有用戶在每個EditText字段中輸入一個號碼和需要顯示的總結果。大約有14 EditText字段和一個TextView

+0

[在Java中查找字符串操作](http://docs.oracle.com/javase/tutorial/java/data/strings.html) – Smit

+0

僅供參考,是要將值相加,還是將它們組合1巨型串? – PearsonArtPhoto

+0

我想將所有的值加在一起並顯示結果。如果用戶輸入12(在一個EditText中),3(在另一個EditText中)和8(在另一箇中),那麼TextView應該顯示23. – DrRoland

回答

0

從每個EditText中獲取文本,並將這些值相加。然後將結果字符串顯示到TextView。下面的僞代碼應該告訴你如何開始。

使用這一位代碼的關鍵是填充tvtextboxes。另外,如果你的數字是浮點數,你將需要改變總數的類型和解析。

ArrayList<EditText> textboxes; 
TextView tv; 
int total=0 
for (edit:textboxes) 
{ 
    total+=Integer.parseInt(edit.getText()); 
} 
tv.setText(text.toString()); 
+0

啊我明白了!我不知道爲什麼我沒有想到使用ArrayList哈哈,我會給這個去看看我得到什麼,謝謝! – DrRoland

+0

我可能是錯的,但從關鍵字*數字*和*總*我認爲@DrRoland想要包含在所有'EditText'字段中的所有數字的總和。 – andr

+0

你對我想要的是正確的,我正在檢查它是否有效。 – DrRoland

0

試試這個:

etUsername = (EditText) findViewById(R.id.etlsUsername); 
etPassword = (EditText) findViewById(R.id.etlsPassword); 
String username = etUsername.getText().toString(); 
String password = etPassword.getText().toString(); 
String text = username + " " + password; 
tv = (TextView) findViewById(R.id.tv); 
tv.setText (text); 

,只要你想只需要添加儘可能多的編輯文本。

如果要總結所有textviews的結果,那麼你就需要通過這樣做是爲了獲得TextView的字符串的整數值:

numone= (EditText) findViewById(R.id.numone); 
numtwo= (EditText) findViewById(R.id.numtwo); 
String numonestring = numone.getText().toString(); 
String numtwostring = numtwo.getText().toString(); 
int one = Integer.valueOf(numonestring); 
int two = Integer.valueOf(numtwostring); 
int sum = one + two; 
tv.setText (sum.toString()); 

等等...

+0

謝謝,這幫了很多! – DrRoland

+0

你爲什麼不接受答案之一? –

0

您也可以使用此:

RelativeLayout rl = (RelativeLayout) findViewById(R.id.mRlayout1); 
    int total = calculate(rl); 
    yourTextView.setText(""+total); 

聲明這個方法:

 // Method called for calculation 
     public int calculate(RelativeLayout layout) { 
      int totalval = 0; 
      for (int i = 0; i < layout.getChildCount(); i++) { 
       View v = layout.getChildAt(i); 
       Class<? extends View> c = v.getClass(); 
       if (c == EditText.class) { 
        EditText et = (EditText) v; 
        totalval += Integer.parseInt(et.getText().toString());           
       } 
      } 
      return totalval; 
     } 
+0

我很困惑,mRlayout1是什麼? – DrRoland

+0

@DrRoland將成爲所有編輯文本的父級佈局。 –

+0

它顯示了一些錯誤,一個錯誤是公衆詮釋計算(RelativeLayout佈局)不能成爲一種方法?我在哪裏放置方法和代碼,你放在該方法之上? – DrRoland

相關問題