android format edittext to display spaces after every 4 characters

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();
    }
});

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(" ", "");