簡體   English   中英

如何將EditText框的輸入限制為小數點后兩個字符?

[英]How can I limit the EditText box input to two characters after a decimal place?

我正在使用帶有EditText框的android應用程序。 在此框中,我希望用戶輸入貨幣。

我已經使用方便的android:inputType =“ numberDecimal”將鍵盤限制為數字和小數,但是我希望能夠阻止用戶在小數點后輸入兩位以上的數字(以便將內容另存為貨幣,也因為我認為讓用戶清楚他們要輸入的內容很重要。

但是我沒有太多的編程經驗,我也不知道從哪里開始尋找(驗證是一個很大的話題哈哈)。 有點谷歌搜索,聽起來我應該對InputFilter類進行自己的擴展,但是我不確定該如何解決或者是否有更好的方法。 因此,任何建議將不勝感激!

嘗試這個

editText.setFilters(new InputFilter[] {new DecimalDigitsInputFilter(2)});

DecimalDigitsInputFilter

public class DecimalDigitsInputFilter implements InputFilter {
    Pattern mPattern;
    public DecimalDigitsInputFilter(int digitsAfterZero) {
        mPattern=Pattern.compile("[0-9]+((\\.[0-9]{0," + (digitsAfterZero-1) + "})?)||(\\.)?");
    }
    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {

        Matcher matcher=mPattern.matcher(dest);       
        if(!matcher.matches())
            return "";
        return null;
    }
}

若要限制用戶在小數點后輸入的位數不超過兩位,請使用以下代碼。

myEditText1 = (EditText) findViewById(R.id.editText1);  
myEditText1.setInputType(3);

數字“ 3”可以解決問題。 希望能幫助到你!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM