2017-03-22 50 views
-1

我想從editText獲取整數,並按下按鈕,在textView中顯示輸入。問題是結果始終爲零。預先感謝您的幫助。Android:將Int轉換爲String和viceversa(在偵聽器中使用try和catch)

EditText editText = (EditText) findViewById(R.id.editText); 
    TextView textView = (TextView) findViewById(R.id.textView); 
    Button button = (Button) findViewById(R.id.button); 
    try{ 
    String string = editText.getText().toString(); 
    int num = Integer.parseInt(string);} 
    catch(NumberFormatException numb){ 
     Toast.makeText(this, "Problem", Toast.LENGTH_SHORT).show(); 
    } 
    button.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      String number = String.valueOf(num); 
      textView.setText(number); 
     } 
    }); 
+3

可能的重複[如何將字符串轉換爲Java中的int?](http://stackoverflow.com/questions/5585779/how-to-convert-a-string-to-an-int-in- java) – HaroldSer

回答

1

你需要閱讀的onClick方法的EditText值來檢索更新值

EditText editText = (EditText) findViewById(R.id.editText); 
TextView textView = (TextView) findViewById(R.id.textView); 
Button button = (Button) findViewById(R.id.button); 

button.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) { 
     try{ 
      String string = editText.getText().toString(); 
      int num = Integer.parseInt(string); // retrieve the updated value 
      String number = String.valueOf(num); 
      textView.setText(number); 
     } 
     catch(NumberFormatException numb){ 
      Toast.makeText(this, "Problem", Toast.LENGTH_SHORT).show(); 
     } 
    } 
}); 
+0

你可以寫代碼嗎? –

+0

代碼已經在回答中 – lubilis

+0

非常感謝。 –

0

你要做的監聽器本身的所有值查找起坐和計算。從我在這裏看到的,當你最初設置「num」時,字符串是空的。

+0

我應該在偵聽器中添加哪些代碼部分? –

+1

除了對象標識符之外的所有內容。 @lubilis對他的例子做出了正確的修改。 –

+0

感謝您的回答。 –