2013-07-31 26 views
9

因此,我正在搞java/android編程,現在我正在試圖製作一個非常基本的計算器。雖然我在這個問題上掛了。這是我的代碼,現在爲獲得數多數民衆贊成在TextView中並使其一個int將textview中的數字轉換爲int

CharSequence value1 = getText(R.id.textView); 
int num1 = Integer.parseInt(value1.toString()); 

,從我可以告訴它是導致錯誤的第二線,但林不知道爲什麼它是這樣做的。它編譯的很好,但是當它試圖運行這部分程序時,它會崩潰我的應用程序。而在textview中唯一的是數字

有什麼建議嗎?

我也可以在必要時

+4

建議:閱讀(和發佈)錯誤。 – kabuko

+0

你能分享一個更詳細的代碼嗎? – Peshal

+0

併發布從'getText()'返回的值以及 – alfasin

回答

2
TextView tv = (TextView)findviewbyID(R.id.textView); 
int num = Integer.valueOf(tv.getText().toString()); 
+2

不要忘記捕捉異常,因爲TextView中的文本可能不是有效數字。 –

+0

Like Gaurav說: int num = Integer.parseInt(tv.getText()。toString()); – Halfacht

0
TextView tv = (TextView)findviewbyID(R.id.textView); 
String text = tv.getText().toString(); 
int n; 
if(text.matches("\\d+")) //check if only digits. Could also be text.matches("[0-9]+") 
{ 
    n = Integer.parseInt(text); 
} 
else 
{ 
    System.out.println("not a valid number"); 
} 
14

您可以在TextView使用閱讀提供更多的我的代碼。

如何聲明它:

TextView tv; 

初始化:

tv = (TextView) findViewById(R.id.textView); 

或:

tv = new TextView(MyActivity.this); 

或者,如果你正在膨脹的佈局,

tv = (TextView) inflatedView.findViewById(R.id.textView); 

要設置字符串爲tv,請使用tv.setText(some_string)tv.setText("this_string")。如果需要設置整數值,請使用tv.setText("" + 5)作爲setText()是一個可以處理字符串和整型參數的重載方法。

要從tv使用tv.getText()得到一個值。

總是檢查解析器是否可以處理textView.getText().toString()可以提供的可能值。如果嘗試解析空字符串(「」),則會引發NumberFormatException。或者,如果您嘗試解析.

String tvValue = tv.getText().toString(); 

if (!tvValue.equals("") && !tvValue.equals(......)) { 
    int num1 = Integer.parseInt(tvValue); 
} 
+1

+1以獲得徹底的答案 – andy256