Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 only for visual purpose. However i need the string without spaces for further usage.

What is the easiest way I can do this?

like image 453
user510164 Avatar asked Apr 20 '12 19:04

user510164


3 Answers

is this editext for credit card?
first create count variable

int count = 0;

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

ccEditText.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start,
                                  int count, int after) { /*Empty*/}

    @Override
    public void onTextChanged(CharSequence s, int start, int before,
                              int count) { /*Empty*/ }

    @Override
    public void afterTextChanged(Editable s) {

        int inputlength = ccEditText.getText().toString().length();

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

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

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

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

            int pos = ccEditText.getText().length();
            ccEditText.setSelection(pos);
        }
        count = ccEditText.getText().toString().length();
    }
});
like image 87
Ario Singgih Permana Avatar answered Oct 15 '22 04:10

Ario Singgih Permana


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 = new StringBuilder(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:

String str = yourTxtView.getText().toString().replace(" ", "");
like image 12
FoamyGuy Avatar answered Oct 15 '22 04:10

FoamyGuy


There is an easier way to achieve this:

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

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

editText.text.toString().replace(" ","")
like image 11
Valentin Avatar answered Oct 15 '22 02:10

Valentin