Good day.

There is an android application, and in it there is (will be) a form for adding a bank card and there is a field for 16-digit number, cvv-code and validity period of a MM / YY card.

The task is as follows: to make so that when entering data in the field "validity period" after entering the first two digits, the symbol "/" is automatically put.

  • TextWatcher to help - iFr0z
  • @ iFr0z is right, you check if there was 1 character, and it became 2, then you add a slash, and if it was 3, and it became 2, then you delete the 2nd character - Vitalii Obideiko

2 answers 2

You can use the TextWatcher interface:

 mEditText.addTextChangedListener(new TextWatcher() { int mCountBefore; int mCountAfter; int mStartNumber; @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { mCountBefore = count; } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { mCountAfter = count; mStartNumber = start; } @Override public void afterTextChanged(Editable s) { if (mCountAfter > mCountBefore && mStartNumber == 1) { s.append("/"); } else if (mCountAfter < mCountBefore && mStartNumber == 2) { s.delete(s.length()-1, s.length()); } if (s.length() == 6) { s.delete(s.length()-1, s.length()); } } }); 

Here is implemented:

  • After entering the second digit in the input box, a slash appears;
  • After removing the slash, the second digit is deleted;
  • Length limit MM/YY .

You can also implement MM/YY mask checking using, for example, regular expressions.

  • Dear post_zeew, please tell me which field field is better to use for this case - user230778
  • @ user230778, This is for regular EditText . - post_zeew
  • This is the text, BUT (!) It is necessary that a keyboard with numbers go out and a string value can be entered into the field since ****** the customer wants the symbol "/" - user230778
  • @ user230778; To do this, add two attributes to EditText : android:inputType="number" and android:digits="0123456789/" . - post_zeew

On the editText instance, call the method addTextChangedListener. This way you can handle text changes.