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?
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:
Whenever you need to get the String without spaces do this:
change the live text while typing is some what difficult. we should handle the following issues.
a. cursor position b. we should allow the user delete the entered text.
The following code handle both the issues.
Add TextWatcher to EditText, and get the text from "afterTextchanged()" and write your logic
String str=""; int strOldlen=0;
Here I am trying to add space for every four characters. After adding first space, then the length of the text is 5. so next space is after 9 characters like that.
if (strLen== 4||strLen==9)
edtAadharNumber.setSelection(edtAadharNumber.getText().length());
Here is a little help function. For your example you would call it with
addPadding(" ", "123456781234", 4);
cleaner version of @Ario's answer which follows the DRY principle: