2013-07-09 18 views
0

下面的代碼試圖獲取兩個EditText值,然後將它們轉換爲整數,然後對它們進行分割並輸出該數值。我沒有運氣,而且在路障之後我只是遇到了路障。我不明白爲什麼從用戶那裏獲得兩個價值並劃分它們似乎非常困難。如果任何人有答案,請詳細解釋它,因爲我是Java/Android的新手,並且想知道事情發生的原因。我現在只是感到沮喪,因爲我在這一個單一的問題上一直在抨擊我一個星期。試圖從EditText中分割值

package com.simplesavinggoal; 

import android.os.Bundle; 
import android.app.Activity; 
import android.view.Menu; 
import android.view.View; 
import android.widget.Button; 
import android.widget.TextView; 
import android.widget.EditText; 

public class MainActivity extends Activity { 

    int finalGoal; 
    EditText goalInput; 
    EditText monthsNum; 
    Button enterGoal; 
    TextView goalOutput; 
    int goalInputInt; 
    int monthsNumInt; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     enterGoal = (Button) findViewById(R.id.btGetGoal); 
     goalOutput = (TextView) findViewById(R.id.tvSavingsGoalAmount); 
     goalInput = (EditText) findViewById(R.id.ndSavingsAmount); 
     monthsNum = (EditText) findViewById(R.id.ndMonthsNum); 

     enterGoal.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 

       goalInputInt = Integer.parseInt(goalInput.getText().toString()); 
       monthsNumInt = Integer.parseInt(monthsNum.getText().toString()); 
       finalGoal = goalInputInt/monthsNumInt; 

       goalOutput.setText(finalGoal); 
         } 
     }); 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.main, menu); 
     return true; 
    } 
} 
+0

什麼不起作用? – neo

+0

你得到什麼錯誤或結果? – andy256

+0

它可能是那個goalOutput.setText(finalGoal); finalGoal是一個整數。調用toString方法就可以了。 setText期望一個字符串不是整數 – neo

回答

0

相反goalOutput.setText(finalGoal),寫入goalOutput.setText( 「」 + finalGoal); (或者,如優雅的方式,Integer.toStirng(finalGoal);)

@Edit 對不起,沒看到,上面的人回答第一。他可能在我面前做了幾秒鐘!

0

我認爲,在android textview中設置文本必須是一個字符串。如果您給出一個整數,那麼它會在具有給定整數的資源中搜索字符串作爲id。 因此,請改爲:

goalOutput.setText(Integer.toString(finalGoal));

2

setText對於TextView應該是setText(CharSequence,TextView.BufferType)

不能輸入int數據類型

只是更改爲

goalOutput.setText(""+finalGoal); 

,我認爲finalGoal不應該int,因爲/的結果將是小數。 將數據類型更改爲double或其他東西

private double finalGoal;