android - 在android中的编辑文本中格式化信用卡

如何让EditText接受格式输入:

4digit 4digit 4digit 4digit 

我试过 Custom format edit text input android to accept credit card number ,但不幸的是我无法删除空格。只要有空间,我就不能删除它。请帮我找出问题。

最佳答案

找到多个“OK”的答案后。我转向了一个更好的 TextWatcher,它旨在独立于 TextView 正常工作。

TextWatcher 类如下:

/**
 * Formats the watched EditText to a credit card number
 */
public static class FourDigitCardFormatWatcher implements TextWatcher {

    // Change this to what you want... ' ', '-' etc..
    private static final char space = ' ';

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }

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

    @Override
    public void afterTextChanged(Editable s) {
        // Remove spacing char
        if (s.length() > 0 && (s.length() % 5) == 0) {
            final char c = s.charAt(s.length() - 1);
            if (space == c) {
                s.delete(s.length() - 1, s.length());
            }
        }
        // Insert char where needed.
        if (s.length() > 0 && (s.length() % 5) == 0) {
            char c = s.charAt(s.length() - 1);
            // Only if its a digit where there should be a space we insert a space
            if (Character.isDigit(c) && TextUtils.split(s.toString(), String.valueOf(space)).length <= 3) {
                s.insert(s.length() - 1, String.valueOf(space));
            }
        }
    }
}

然后像添加任何其他 TextWatcher 一样将其添加到您的 TextView。

{
  //...
  mEditTextCreditCard.addTextChangedListener(new FourDigitCardFormatWatcher()); 
}

这将自动删除空间,这样用户在编辑时实际上可以减少击键次数。

警告

如果您使用的是 inputType="numberDigit",这将禁用 '-' 和 ' ' 字符,因此我建议使用 inputType="phone"。这会启用其他字符,但只需使用自定义输入过滤器即可解决问题。

https://stackoverflow.com/questions/11790102/

相关文章:

java - Java 中的 String.format() 和十六进制数字

javascript - 最好的 JavaScript 日期解析器和格式化程序?

c# - 使用c#的两个小数位

string - Scala 中更好的字符串格式

php - 如何在 PHP 中将数字格式化为美元金额

c# - C# 有自动代码格式化程序吗?

java - 如何从 Java 中的输入文本中删除标点符号?

python - 如何很好地格式化dict字符串输出

c# - DataContractSerializer 创建的 XML 格式

xml - XML 中的引号。单人还是双人?