0
@OnTextChanged(value = R.id.credit_card_number, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)        
void onTextChanged(Editable text) {
        int length = text.length();
        int lastIndex = length - 1;

        InputFilter[] filters = text.getFilters();
        // Disable input filters
        text.setFilters(new InputFilter[] {});
        if (length > 0) {
            if (TextUtils.lastIndexOf(text, '-') != lastIndex && length % 5 == 0) {
                text.insert(lastIndex, mContext.getString(R.string.dash));
            } else {
                text.delete(lastIndex, lastIndex);
            }
        }
    }

According to the current scenario I can generate the following string pattern. 1234-4564-5676 But issue is that if I tried to enter a value in between numbers my format get break.as a example 12534-4564-5676 What I need to make 1253-4456-4567-6.

Is there any possible way to do that with minimal changes? Thank in advance.

Rajitha Perera
  • 1,581
  • 5
  • 26
  • 42

2 Answers2

0

You can use the below class for formatting what you are trying to do-

class CreditCardNumberFormattingTextWatcher : TextWatcher {
private var current = ""

override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
}

override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
}

override fun afterTextChanged(s: Editable) {
    if (s.toString() != current) {
        val userInput = s.toString().replace("[^\\d]".toRegex(), "")
        if (userInput.length <= 16) {
            val sb = StringBuilder()
            for (i in 0..userInput.length - 1) {
                if (i % 4 == 0 && i > 0) {
                    sb.append(" ")
                }
                sb.append(userInput[i])
            }
            current = sb.toString()

            s.filters = arrayOfNulls<InputFilter>(0)
        }
        s.replace(0, s.length, current, 0, current.length)
    }
}
}
Shivam Yadav
  • 958
  • 11
  • 23
0

Instead of OnTextChanged you can use TextWatcher class.

code

editText.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    @Override
    public void afterTextChanged(Editable editable) {
        int length = editable.length();
        int lastIndex = length - 1;

        // Disable input filters
        editable.setFilters(new InputFilter[] {});
        if (length > 0) {
            if (TextUtils.lastIndexOf(editable, '-') != lastIndex && length % 5 == 0) {
                editable.insert(lastIndex, "#");
            } else {
                editable.delete(lastIndex, lastIndex);
            }
        }
    }
});

Hope this will solve your problem.

Bharat Vankar
  • 317
  • 2
  • 13