如何让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/