Reputation: 887
In my app I have to format the input of two EditTexts like:
I don't know how to do it. Please help:
Upvotes: 1
Views: 3620
Reputation: 983
Put a listener on the edit text as afterTextChanged. Get the number of digits by using the length() function. Once you get the number of digits, you can extract each digit and then insert space of '/' at the appropriate place.
len=editText.getText.toString().length();
then you can do the appropriate change by checking the length.
num=Integer.parseInt(editText.getText.toString());
temp=num;
if(len>=10)
{
A:
if((len-4)>0)
{
for(i=0;i<(len-4);i++)
{
temp=temp/10; //we get the first 4 digits
}
editText.setText(temp+" "); //place letters and add space
temp=num%(10^(len-4)); //get the num without the first-4 letters
len=len-4; //modify length
goto A; //repeat again
}
editText.setText(temp); //add the last remaining letters
}
else if(len==4)
{
temp=num;
temp=temp%100; //store the last 2 digits
num=num/10; //get the first 2 digits
editText.setText(num+"/"+temp);
}
i havnt tried this but i think this will work. Hope this will help. :)
Upvotes: 2
Reputation: 22537
I can think of two ways of achieving it:
Use addTextChangedListener
:
yourEditText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
// Do your tricks here
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {}
});
Upvotes: 1
Reputation: 748
Use "onKeyListener" to get the input event. EditText OnKeyDown
Then check for correct input and count the digits. Add the whitespace/slash in your code. Sample code:
if (editText.getText.toString().length() % 4 == 0) editText.setText(editText.getText.toString() + " ");
Didn't try it by myself, but this would be the way i would try. In addition i would check for numeric input too.
Upvotes: 1