如何让的EditText
接受输入格式为:
How to make EditText
accept input in format:
4digit 4digit 4digit 4digit
我试过Custom格式编辑文本输入的Android接受信用卡号码,但不幸的是我无法删除的空间。每当有一个空间,我无法将其删除。请帮我找出这个问题。
I tried Custom format edit text input android to accept credit card number, but unfortunately I was unable to delete the spaces. Whenever there is a space, I could not to delete it. Please help me in finding out the issue.
发现多个答案是OK之后。我走向更加美好的TextWatcher其目的是从正常和独立工作的的TextView
。
After finding multiple answers that are 'OK'. I moved towards a better TextWatcher which is designed to work correctly and independently from the TextView
.
TextWatcher类如下:
TextWatcher class is as follows:
/**
* 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));
}
}
}
}
然后将其添加到您的TextView,就像任何其他的 TextWatcher
。
{
//...
mEditTextCreditCard.addTextChangedListener(new FourDigitCardFormatWatcher());
}
这将自动删除空间理智回去,使用户可以真正做到少击键时的编辑。
This will auto delete the space sensibly going back so the user can actually do less keystrokes when editing.
如果您使用的是 inputType =numberDigit
这将禁用' - '和''字符,所以我推荐使用 inputType = 手机
。这使得其他的字符,而只是使用自定义输入过滤器和问题就解决了。
If you are using inputType="numberDigit"
this will disable the '-' and ' ' chars, so I recommend using, inputType="phone"
. This enables other chars, but just use a custom inputfilter and problem solved.