简体   繁体   English

将掩码应用于Android上的EditText的最佳方法是什么?

[英]what's the best way to apply a mask to an EditText on Android?


what's the best way to mask a EditText on Android? 什么是在Android上屏蔽EditText的最佳方式?
I Would like my EditText to behave like this decimal number input here . 我想我的EditText在这里输入像这个十进制数字。 Is there a easy way to do this? 有一个简单的方法来做到这一点?

You have to programmatically set an InputFilter on your EditText by setFilters . 您必须通过setFilters以编程方式在EditText上设置InputFilter

From the documentation: 从文档:

InputFilters can be attached to Editables to constrain the changes that can be made to them. 可以将InputFilters附加到Editables以约束可以对其进行的更改。

You can even change the users input, for example by adding a decimal point which is what you want if I get you correctly. 您甚至可以更改用户输入,例如通过添加小数点,如果我能正确找到您想要的小数点。

I built a decimal mask for an edit text that will auto change the edit text to the number of decimal places you want. 我为编辑文本构建了一个十进制掩码,它会自动将编辑文本更改为您想要的小数位数。 Bascially, you listen for text changes and loss of focus. 基本上,您会听取文本更改和失去焦点。

    private void formatNumber() {
    sNumberToFormat = etNumberToFormat.getText().toString();
    sDecimalMask = etDecimalMask.getText().toString();
    boolean periodMask = false;
    String delimiter = getDelimiter();
    String[] decimalMask = getsDecimalMask();


    if (decimalMask.length == 1) {
        return;
    } else {

        if (delimiter.equalsIgnoreCase(",")) {
            //decimal format only currently works with dot delimiters.
            sDecimalMask = sDecimalMask.replace(",", ".");
        }

        DecimalFormat df = new DecimalFormat(sDecimalMask);
        df.setRoundingMode(RoundingMode.UP);

        sNumberToFormat = df.format(Float.valueOf(sNumberToFormat.replace(",", ".")));
        //if (maxNumber > Float.valueOf(sNumberToFormat)) {
        if (delimiter.equalsIgnoreCase(",")) {
            sNumberToFormat = sNumberToFormat.replace(".", ",");
        }
        etNumberToFormat.setText(sNumberToFormat);

    }

}

The complete demo is here . 完整的演示在这里

I think you can use: 我想你可以用:

android:numeric="decimal"

on your EditText 在您的EditText上

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM