2012-02-22 93 views
1

我正在使用磁盤空間計算器,我需要根據用戶輸入動態計算一些值。我的應用程序中有一個EditText元素接收數字。我想調用函數calculate(),當用戶在文本字段中輸入一個值時,它將自動計算其他值。這裏是我的代碼,它當EditText爲空時,用於動態計算的Android崩潰

//fps is my EditText element 
this.fps.addTextChangedListener(new TextWatcher() { 
    @Override 
    public void onTextChanged(CharSequence s, int start, int before, int count) 
      { 
    // TODO Auto-generated method stub 
     calculate(); 
    } 
    @Override 
    public void beforeTextChanged(CharSequence s, int start, int count, 
       int after) { 
    // TODO Auto-generated method stub 
    } 
    @Override 
    public void afterTextChanged(Editable s) { 
    // TODO Auto-generated method stub 

    } 
    });  

我的計算()函數使用文本輸入,將其轉換成浮點計算像其他帶寬值。它工作正常,但問題出現時,我想刪除EditText中的所有數字添加另一個。在editText中沒有任何內容的時候,它會發出異常。我的理解,這是因爲沒有什麼可以轉化爲浮動這樣解析異常等 我試圖把一個默認值

if(fps.getText().length==0) 
    fps.setText("1"); 

但它不工作。我怎麼解決這個問題?

回答

3

只是試圖環繞你calculate()用try/catch塊,趕上拋出的異常..

try { 
    calculate(); 
} catch {NumberFormatException nfe) { //or whatever exception you get 
     //do some handling if you need to 
} 
1

試試這個:

this.fps.addTextChangedListener(new TextWatcher() { 
    @Override 
    public void onTextChanged(CharSequence s, int start, int before, int count) { 

    } 
    @Override 
    public void beforeTextChanged(CharSequence s, int start, int count, 
       int after) { 

    } 
    @Override 
    public void afterTextChanged(Editable s) { 

     if(!s.toString().trim().equals("")) 
      calculate(); 
     else 
      //do nothing here or show error 
    } 
}); 
+0

非常感謝我的解決方案,我嘗試了它,它的工作原理+1,但因爲我不能接受多個答案,我想我會使用try catch塊解決方案。 – Anila 2012-02-22 13:38:50

1

您的操作嘗試當你的edittext中至少有一個字符是這樣的時,在onTextChanged()中調用你的calculate()。

if(fps.getText.length>0){ 
calculate(); 
} 
+0

感謝您的回答 – Anila 2012-02-22 13:44:56