2011-02-25 34 views
0

我有一個EditText(接受0-9)與一個監聽器。我想在輸入時輸入它,應用一個計算,並將它顯示在同一個EditText框中。實時過濾輸入?

該框最初顯示$ 0.00。當用戶輸入2時,我想從盒子中抓取它,解析它以除去$和decimal,將其轉換爲int ...將其除以100,並將$放在它的前面。在setText之後,它應該顯示$ 0.02。如果他們然後按5,我會抓住它,解析它,結束了25,做數學,它應該顯示$ 0.25等。

我不知道這是最好的方式,我是接受新的想法。這裏是我當前的代碼:

mEditPrice.addTextChangedListener(new TextWatcher(){ 
     DecimalFormat dec = new DecimalFormat("0.00"); 
     @Override 
     public void afterTextChanged(Editable arg0) { 
     } 
     @Override 
     public void beforeTextChanged(CharSequence s, int start, 
       int count, int after) { 
     } 
     @Override 
     public void onTextChanged(CharSequence s, int start, 
       int before, int count) { 
      String userInput = mEditPrice.getText().toString().replaceAll("[^\\d]", ""); 
      int userInputInt = Integer.parseInt(userInput); 
      mEditPrice.setText("$"+dec.format(userInputInt/100)); 
     } 

回答

1

有幾個問題來處理這裏之前,你可以達到你想要的那種功能。

  1. 無論何時處理TextWatcher,在設置被監視的EditText對象的文本時都需要小心。原因是每次你調用setText時,它都會再次觸發觀察者,導致你的代碼進入無限循環。

    爲了防止出現這種情況,您應該將要設置的文本的值設置爲onTextChanged方法之外的變量。輸入方法時,請檢查該變量,如果值與CharSequence不同,則只執行處理代碼。

  2. 的整數變量userInputInt,當除以100,將等於零。

    這應改爲雙重產生類似0.02等

  3. 值的這些變化後,我們可以得到的EditText進入一個2後顯示$ 0.02,但因爲我們設定的值在代碼中的EditText中,EditText的下一個條目將被添加到文本的開頭。那麼如果我們輸入'5',我們得到50.02美元。

    爲了克服這個問題,我們需要做的最後一件事就是使用set position方法將EditText的位置設置爲字符串的末尾。

下面是最終的解決方案:

private String value; 

mEditPrice.addTextChangedListener(new TextWatcher(){ 
    DecimalFormat dec = new DecimalFormat("0.00"); 

    @Override 
    public void afterTextChanged(Editable arg0) { 
    } 

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

    @Override 
    public void onTextChanged(CharSequence s, int start, int before, int count) { 
     if (!s.toString().equals(value)){ 
      String userInput = mEditPrice.getText().toString().replaceAll("[^\\d]", ""); 
      double userInputDouble = Double.parseDouble(userInput); 
      value = ("$"+dec.format(userInputDouble/100)); 

      mEditPrice.setText(value); 
      mEditPrice.setSelection(value.length()); 
     } 
    } 
}); 
+0

作品完美,謝謝! – Roger 2011-02-25 15:54:33