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?
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(" ", "");
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(" ","")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With