2012-06-26 33 views
1

全部 - 我一直在爲此苦苦掙扎了一段時間,並查看了所有關於此類問題的其他問題,但我無法弄清楚:我有一個edttext字段,需要格式化爲貨幣。我已經嘗試了與此有關的所有其他問題中的代碼,但無論我嘗試什麼,都不起作用。以下是我的代碼:問題格式化貨幣編輯文本

EditText text = (EditText)findViewById(R.id.edit_bill); 

    text.setRawInputType(Configuration.KEYBOARD_12KEY);  

    text.addTextChangedListener(new TextWatcher(){ 
     EditText text = (EditText)findViewById(R.id.edit_bill); 
     DecimalFormat dec = new DecimalFormat("0.00"); 
     public void afterTextChanged(Editable arg0) { 
     } 
     public void beforeTextChanged(CharSequence s, int start, 
       int count, int after) { 
     } 
     public void onTextChanged(CharSequence s, int start, 
       int before, int count) { 
      if(!s.toString().matches("^\\$(\\d{1,3}(\\,\\d{3})*|(\\d+))(\\.\\d{2})?$")) 
      { 
       String userInput= ""+s.toString().replaceAll("[^\\d]", ""); 
       if (userInput.length() > 0) { 
        Float in=Float.parseFloat(userInput); 
        float percen = in/100; 
        text.setText("$"+dec.format(percen)); 
        text.setSelection(text.getText().length()); 
       } 
      } 
     } 
    }); 

此代碼位於onClick方法中。這是否有所作爲(例如,僅當用戶單擊按鈕時,文本纔會被格式化)?提前致謝!

+0

['onTextChanged'](http://developer.android.com/reference/android/text/TextWatcher.html#onTextChanged%28java.lang.CharSequence,%20int,%20int,%20int%29)does not像那樣工作。你不能修改'onTextChanged'中的文字。 –

+0

好的,那麼我如何格式化貨幣? afterTextChanged? – ninge

回答

2

我以前用這種方法來格式化錢。

static public String customFormat(String pattern, double s) { 
    DecimalFormat myFormatter = new DecimalFormat(pattern); 
    String stringFormatOutput = myFormatter.format(s); 
    return stringFormatOutput; 
} 

可以像這樣使用:

String strPrice = customFormat("$###,##0.00", 300.2568); 
mTxt.setText(strPrice); 

只是改變了 「300.2568」 是你的價格。這可能也適用於花車而不是雙打。

+0

感謝您的幫助! – ninge