In my app I have to format the input of two EditTexts like:

  • 1234 4567 67: Ten digits that grouped by four. (The space is automatically, not inserted by user)
  • 11/14: Four digits that separated by '/'. (The '/' is inserted automatically)

I don't know how to do it. Please help:

有帮助吗?

解决方案 2

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) {}
       });
  • Create custom Edittexts
    This link wont do what you are looking for, but will give you an idea how to create custom EditText.

其他提示

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. :)

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top