Forked from epool/CreditCardFormattingTextWatcher.java
Created
February 22, 2017 17:57
-
-
Save Felipe00/9a2a9733abdd3bad15ae9eef249b2d42 to your computer and use it in GitHub Desktop.
Text watcher for giving "#### #### #### ####" format to edit text.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import android.text.Editable; | |
| import android.text.TextWatcher; | |
| /** | |
| * Text watcher for giving "#### #### #### ####" format to edit text. | |
| * Created by epool on 3/14/16. | |
| */ | |
| public class CreditCardFormattingTextWatcher implements TextWatcher { | |
| private static final String EMPTY_STRING = ""; | |
| private static final String WHITE_SPACE = " "; | |
| private String lastSource = EMPTY_STRING; | |
| @Override | |
| public void beforeTextChanged(CharSequence s, int start, int count, int after) { | |
| } | |
| @Override | |
| public void onTextChanged(CharSequence s, int start, int before, int count) { | |
| } | |
| @Override | |
| public void afterTextChanged(Editable s) { | |
| String source = s.toString(); | |
| if (!lastSource.equals(source)) { | |
| source = source.replace(WHITE_SPACE, EMPTY_STRING); | |
| StringBuilder stringBuilder = new StringBuilder(); | |
| for (int i = 0; i < source.length(); i++) { | |
| if (i > 0 && i % 4 == 0) { | |
| stringBuilder.append(WHITE_SPACE); | |
| } | |
| stringBuilder.append(source.charAt(i)); | |
| } | |
| lastSource = stringBuilder.toString(); | |
| s.replace(0, s.length(), lastSource); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment