Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package de.brudaswen.util.format;
- import android.text.Editable;
- import android.text.TextWatcher;
- /**
- * Format input inside {@link android.widget.EditText} and make character blocks.
- * <p>
- * <p>
- * IBAN: <code>XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX</code>
- * <p>
- * Credit card: <code>XXXX XXXX XXXX XXXX</code>
- *
- * @author Sven Obser (sven@brudaswen.de)
- */
- public class NumberBlockWatcher implements TextWatcher {
- private static final int NO_MAX_CHARS = -1;
- /**
- * Create default IBAN text watch:
- * <p>
- * Style: <code>XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX</code>
- */
- public static NumberBlockWatcher getIbanNumberBlockWatcher() {
- return new NumberBlockWatcher(4, ' ', true, 36);
- }
- /**
- * Create default credit card text watch:
- * <p>
- * Style: <code>XXXX XXXX XXXX XXXX</code>
- */
- public static NumberBlockWatcher getCreditCardNumberBlockWatcher() {
- return new NumberBlockWatcher(4, ' ', false, 16);
- }
- private final int size;
- private final char space;
- private final boolean toUpper;
- private final int maxChars;
- /**
- * Create Iban text watcher with custom properties.
- *
- * @param size Size of the character blocks.
- * @param space Spacing character between blocks.
- * @param toUpper Change characters to uppercase.
- * @param maxChars Max number of chars (excluding space) or {@link #NO_MAX_CHARS} to disable.
- */
- public NumberBlockWatcher(int size, char space, boolean toUpper, int maxChars) {
- this.size = size + 1;
- this.space = space;
- this.toUpper = toUpper;
- if (maxChars > NO_MAX_CHARS) {
- this.maxChars = maxChars + maxChars / size - 1;
- } else {
- this.maxChars = NO_MAX_CHARS;
- }
- }
- @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) {
- for (int i = 0; i < s.length(); ) {
- final char c = s.charAt(i);
- if (isSpacePosition(i) && c != space) {
- // Insert missing space
- s.insert(i, String.valueOf(space));
- i++;
- } else if (!isSpacePosition(i) && c == space) {
- // Delete wrongly placed space and check position again
- s.delete(i, i + 1);
- } else if (toUpper && !isSpacePosition(i) && Character.isLowerCase(c)) {
- s.replace(i, i + 1, String.valueOf(Character.toUpperCase(c)));
- } else {
- // Everything all right
- i++;
- }
- }
- if (maxChars > NO_MAX_CHARS && s.length() > maxChars) {
- s.delete(maxChars, s.length());
- }
- }
- private boolean isSpacePosition(int i) {
- return (i + 1) % size == 0;
- }
- }
Add Comment
Please, Sign In to add comment