自定义格式编辑文本inputandroid接受信用卡号码

如何使编辑文本接受格式input

4digitnumber-4dignumber-4dignumber-4dignumber 

代码

 text.addTextChangedListener(new TextWatcher() { int len = 0; String string ; @Override public void afterTextChanged(Editable s) { text.setOnKeyListener(new OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_DEL) { } else{ string = text.getText().toString(); len = string.length()+1; if(len%5==0){text.append("-");} } return false; } }); } }); 

添加时工作正常,但删除或编辑会导致问题。

Solutions Collecting From Web of "自定义格式编辑文本inputandroid接受信用卡号码"

现在,这适用于所有删除/编辑操作的软/硬键盘。 tx 4你的帮助..

 package com.and; import android.app.Activity; import android.app.AlertDialog; import android.inputmethodservice.KeyboardView; import android.os.Bundle; import android.telephony.PhoneNumberFormattingTextWatcher; import android.text.Editable; import android.text.Selection; import android.text.Spannable; import android.text.TextWatcher; import android.text.format.Formatter; import android.text.method.NumberKeyListener; import android.view.KeyEvent; import android.view.View; import android.view.View.OnKeyListener; import android.widget.EditText; import android.widget.Toast; public class ccformat extends Activity { String a; int keyDel; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final EditText text = (EditText) findViewById(com.and.R.id.editText1); text.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { boolean flag = true; String eachBlock[] = text.getText().toString().split("-"); for (int i = 0; i < eachBlock.length; i++) { if (eachBlock[i].length() > 4) { flag = false; } } if (flag) { text.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_DEL) keyDel = 1; return false; } }); if (keyDel == 0) { if (((text.getText().length() + 1) % 5) == 0) { if (text.getText().toString().split("-").length <= 3) { text.setText(text.getText() + "-"); text.setSelection(text.getText().length()); } } a = text.getText().toString(); } else { a = text.getText().toString(); keyDel = 0; } } else { text.setText(a); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable s) { } }); } } 

这是工作:

 public class EditTextSample extends Activity { // This regexp has to be improved, it does not detect case where you have // more than 4 digits in a middle group like: 1234-12345-123 static final Pattern CODE_PATTERN = Pattern.compile("([0-9]{0,4})|([0-9]{4}-)+|([0-9]{4}-[0-9]{0,4})+"); /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.edit_text_sample); final EditText editText = (EditText) findViewById(R.id.input); editText.addTextChangedListener(new TextWatcher() { @Override public void afterTextChanged(Editable s) { Log.w("", "input" + s.toString()); if (s.length() > 0 && !CODE_PATTERN.matcher(s).matches()) { String input = s.toString(); String numbersOnly = keepNumbersOnly(input); String code = formatNumbersAsCode(numbersOnly); Log.w("", "numbersOnly" + numbersOnly); Log.w("", "code" + code); editText.removeTextChangedListener(this); editText.setText(code); // You could also remember the previous position of the cursor editText.setSelection(code.length()); editText.addTextChangedListener(this); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } private String keepNumbersOnly(CharSequence s) { return s.toString().replaceAll("[^0-9]", ""); // Should of course be more robust } private String formatNumbersAsCode(CharSequence s) { int groupDigits = 0; String tmp = ""; for (int i = 0; i < s.length(); ++i) { tmp += s.charAt(i); ++groupDigits; if (groupDigits == 4) { tmp += "-"; groupDigits = 0; } } return tmp; } }); } } 

在我的情况下,代码工作正常。

 editTextCreditCard.addTextChangedListener(new FourDigitCardFormatWatcher()); 

TextWatcher添加自定义类。

 public class FourDigitCardFormatWatcher implements TextWatcher { 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) { 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()); } } if (s.length() > 0 && (s.length() % 5) == 0) { char c = s.charAt(s.length() - 1); if (Character.isDigit(c) && TextUtils.split(s.toString(), String.valueOf(space)).length <= 3) { s.insert(s.length() - 1, String.valueOf(space)); } } } } 

希望这会帮助你。

在我看来,这里给出的答案不能正常使用删除,从中间操作删除等,这是我的代码。 它不限制input的长度,但似乎可以与各种插入和删除确定:

 import android.text.Editable; import android.text.TextWatcher; import android.view.KeyEvent; import android.view.View; import android.widget.EditText; public class HyphenDelimitTextWatcher implements TextWatcher { EditText mEditText; boolean mInside = false; boolean mWannaDeleteHyphen = false; boolean mKeyListenerSet = false; final static String MARKER = "|"; // filtered in layout not to be in the string @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { if(!mKeyListenerSet) { mEditText.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { try { mWannaDeleteHyphen = (keyCode == KeyEvent.KEYCODE_DEL && mEditText.getSelectionEnd() - mEditText.getSelectionStart() <= 1 && mEditText.getSelectionStart() > 0 && mEditText.getText().toString().charAt(mEditText.getSelectionEnd() - 1) == '-'); } catch (IndexOutOfBoundsException e) { // never to happen because of checks } return false; } }); mKeyListenerSet = true; } } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (mInside) // to avoid recursive calls return; mInside = true; int currentPos = mEditText.getSelectionStart(); String string = mEditText.getText().toString().toUpperCase(); String newString = makePrettyString(string); mEditText.setText(newString); try { mEditText.setSelection(getCursorPos(string, newString, currentPos, mWannaDeleteHyphen)); } catch (IndexOutOfBoundsException e) { mEditText.setSelection(mEditText.length()); // last resort never to happen } mWannaDeleteHyphen = false; mInside = false; } @Override public void afterTextChanged(Editable s) { } private String makePrettyString(String string) { String number = string.replaceAll("-", ""); boolean isEndHyphen = string.endsWith("-") && (number.length()%4 == 0); return number.replaceAll("(.{4}(?!$))", "$1-") + (isEndHyphen ?"-":""); } private int getCursorPos(String oldString, String newString, int oldPos, boolean isDeleteHyphen) { int cursorPos = newString.length(); if(oldPos != oldString.length()) { String stringWithMarker = oldString.substring(0, oldPos) + MARKER + oldString.substring(oldPos); cursorPos = (makePrettyString(stringWithMarker)).indexOf(MARKER); if(isDeleteHyphen) cursorPos -= 1; } return cursorPos; } public HyphenDelimitTextWatcher(EditText editText) { mEditText = editText; } } 

用法:

  mSomeEditText.addTextChangedListener(new HyphenDelimitTextWatcher(mSomeEditText)); 

如果你需要这个效果,你可以在EditText中使用这个代码

在这里输入图像说明