Skip to content Skip to sidebar Skip to footer

Android Format Edittext To Display Spaces After Every 4 Characters

Android - I want to get a number input from the user into an EditText - it needs to be separated by spaces - every 4 characters. Example: 123456781234 -> 1234 5678 1234 This is

Solution 1:

is this editext for credit card? first create count variable

int count = 0;

then put this in your oncreate(activity) / onviewcreated(fragment)

ccEditText.addTextChangedListener(newTextWatcher() {
    @OverridepublicvoidbeforeTextChanged(CharSequence s, int start,
                                  int count, int after) { /*Empty*/}

    @OverridepublicvoidonTextChanged(CharSequence s, int start, int before,
                              int count) { /*Empty*/ }

    @OverridepublicvoidafterTextChanged(Editable s) {

        intinputlength= ccEditText.getText().toString().length();

        if (count <= inputlength && inputlength == 4 ||
                inputlength == 9 || inputlength == 14)){

            ccEditText.setText(ccEditText.getText().toString() + " ");

            intpos= ccEditText.getText().length();
            ccEditText.setSelection(pos);

        } elseif (count >= inputlength && (inputlength == 4 ||
                inputlength == 9 || inputlength == 14)) {
            ccEditText.setText(ccEditText.getText().toString()
                    .substring(0, ccEditText.getText()
                            .toString().length() - 1));

            intpos= ccEditText.getText().length();
            ccEditText.setSelection(pos);
        }
        count = ccEditText.getText().toString().length();
    }
});

Solution 2:

as @waqas pointed out, you'll need to use a TextWatcher if your aim is to make this happen as the user types the number. Here is one potential way you could achieve the spaces:

StringBuilder s;
s = newStringBuilder(yourTxtView.getText().toString());

for(int i = 4; i < s.length(); i += 5){
    s.insert(i, " ");
}
yourTxtView.setText(s.toString());

Whenever you need to get the String without spaces do this:

Stringstr = yourTxtView.getText().toString().replace(" ", "");

Solution 3:

There is an easier way to achieve this:

editText.doAfterTextChanged { text ->
    valformattedText= text.toString().replace(" ", "").chunked(4).joinToString(" ")
    if (formattedText != text.toString()) {
        editText.setText(formattedText)
    }
}

When you want to get the text without space, just do:

editText.text.toString().replace(" ","")

Solution 4:

You need to use TextWatcher to achieve visual purpose spaces.

And use any simply split string by space logic to join it back or loop through the entire string per character wise and eliminate (char) 32 from the string

Solution 5:

I have created a class that encapsulates the given behavior.

/**
 * Custom [TextWatcher] class that appends a given [separator] for every [interval].
 */abstractclassSeparatorTextWatcher(
    privateval separator: Char,
    privateval interval: Int
) : TextWatcher {

    privatevar dirty = falseprivatevar isDelete = falseoverridefunafterTextChanged(editable: Editable?) {
        if (dirty) return

        dirty = trueval text = editable.toString().handleSeparator()
        onAfterTextChanged(text)
        dirty = false
    }

    overridefunbeforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        // Empty
    }

    overridefunonTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        isDelete = before != 0
    }

    privatefun String.handleSeparator(): String {
        val stringBuilder = StringBuilder(this)

        if (length > 0 && length.rem(interval + 1) == 0) {
            if (isDelete) {
                stringBuilder.deleteCharAt(length - 1)
            } else {
                stringBuilder.insert(length - 1, separator)
            }
        }

        return stringBuilder.toString()
    }

    /**
     * Subclasses must implement this method to get the formatted text.
     */abstractfunonAfterTextChanged(text: String)
}

Here's a snippet on how to use it:

editText.addTextChangedListener(object : SeparatorTextWatcher(' ', 4) {
            overridefunonAfterTextChanged(text: String) {
                editText.run {
                    setText(text)
                    setSelection(text.length)
                }
            }
        })

Post a Comment for "Android Format Edittext To Display Spaces After Every 4 Characters"