2012-02-17 95 views
3

我想在我的編輯文本中只顯示兩位小數,ofc我想在編輯文本中顯示貨幣,但將其值限制爲小數點後兩位數。使EditText只顯示兩位小數

我看到了一些使用正則表達式的解決方案,但我不想那樣做。我已經被告知,Java支持一些內部庫函數可以做到這一點。任何人都可以給我提示或給我一些有效的代碼。

問候

amount.setRawInputType(Configuration.KEYBOARD_12KEY); 

     amount.addTextChangedListener(new TextWatcher() 
     { 

      @Override 
      public void onTextChanged(CharSequence s, int start, int before, int count) { 
       // TODO Auto-generated method stub 
       DecimalFormat formatVal = new DecimalFormat("##.##"); 
       String formatted = formatVal.format(s); 
       amount.setText(formatted); 

      } 
+0

你有沒有想過實施某種2槽選取器?只是一個想法。也許更友好的用戶體驗。 – 2012-02-17 05:58:53

回答

8

您可以簡單地使用DecimalFormat

DecimalFormat format = new DecimalFormat("##.##"); 
String formatted = format.format(22.123); 
editText.setText(formatted); 

您將獲得導致EditText22.12

+0

可以請您澄清一下,如何使用它? – 2012-02-17 05:59:50

+0

我編輯了我的答案。 – 2012-02-17 06:01:47

+0

好的我已經把這段代碼放在onTextChanged屬性中。它給予非法論證例外。任何想法? – 2012-02-17 06:13:56

0

你只需要分配setKeyListener()EditText

myEditText.setKeyListener(DigitsKeyListener.getInstance(true,true)); 

返回DigitsKeyListener即0到9接受數字,如果加指定的減號(僅在開始時)和/或小數點(每場只有一個)。

3

這是一個解決方案,它將限制用戶在編輯文本中輸入內容。

InputFilter filter = new InputFilter() { 
    final int maxDigitsBeforeDecimalPoint=2; 
    final int maxDigitsAfterDecimalPoint=2; 

    @Override 
    public CharSequence filter(CharSequence source, int start, int end, 
      Spanned dest, int dstart, int dend) { 
      StringBuilder builder = new StringBuilder(dest); 
      builder.replace(dstart, dend, source 
        .subSequence(start, end).toString()); 
      if (!builder.toString().matches(
        "(([1-9]{1})([0-9]{0,"+(maxDigitsBeforeDecimalPoint-1)+"})?)?(\\.[0-9]{0,"+maxDigitsAfterDecimalPoint+"})?" 

        )) { 
       if(source.length()==0) 
        return dest.subSequence(dstart, dend); 
       return ""; 
      } 

     return null; 

    } 
}; 

mEdittext.setFilters(new InputFilter[] { filter }); 

例如,12.22所以只允許輸入前兩位數字和小數位後兩位數字。