简体   繁体   中英

Android Limit EditText to Integer input only

I am trying to apply some kind of verification to an edittext. A user should only be able to enter integers between 1 and 60. I am wondering whether I should let them type whatever they like and when they focus off of the edittext check the contents and if it is out of bounds change the value to a default, say 0.

Or is there a way to limit the keyboard to only allow integers?

UPDATE: I am doing everything programmatically. So far I have been able to limit to only numeric input and have a maximum of 2 characters by implementing the following. I am still struggling to limit only values between 0 and 60 though.

    editText.setInputType( InputType.TYPE_CLASS_NUMBER );
    InputFilter[] FilterArray = new InputFilter[1];
    FilterArray[0] = new InputFilter.LengthFilter(2);
    editText.setFilters(FilterArray);

You can make use of android.text.method.KeyListener to replace the current input with whatever you like.

Since you dont have to change all the keys you can use addTextChangedListener(TextWatcher watcher) method like this:

EditText editT = (EditText) findViewById(R.id.your_id);
editT.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
    // TODO Auto-generated method stub
}

@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    // TODO Auto-generated method stub
}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
    // TODO Auto-generated method stub

});

Make use of it to check whether your input is beyond what you are looking and you can even neglect the keys by checking on that loop.

In XML:

  • If you are using numbers only use android:inputType="number" .
  • To limit the no of digits to 2 include android:maxLength="2" .

If you limit to numbers only, you could use the

EditText.addTextChangedListener

to get the value inputed and verify it's not over 60

You can easily allow only numbers by adding android:numeric="integer" to the EditText in the layout xml file

Though it is worth mentioning that android:numeric="integer" is now deprecated

I've got it! I scoured the internet forever, and put a few things together to get it to work. Basically what it does is runs a parallel process that will be constantly running while the user has their focus on the particular edittext box. It will set a filter so that the user can only enter 0-5 in the first integer slot, but will be allowed to enter 0-9 for the second. This will obviously give 0-59 instead of 1-60, but that's what you want for seconds anyways. This code goes before the onCreate method, inside of your class:

final InputFilter filter = new InputFilter() 
{
    public CharSequence filter(CharSequence source, int start, int end,
                Spanned dest, int dstart, int dent)
    {
        for (int i = start; i < end; i++)
        {
            if ((source.charAt(start) == "6".charAt(0)) || (source.charAt(start) == "7".charAt(0)) || (source.charAt(start) == "8".charAt(0))
                    || (source.charAt(start) == "9".charAt(0)) || (!Character.isDefined(source.charAt(i))) )                            
            {
                return "";
            }
        }
        return null;
    }
 };

private class FilterCheckerTask extends AsyncTask<Void, Void, Void>
{       
    @Override
    protected Void doInBackground(Void... params) 
    {           
        while(true)
        {               
            if (<EditText>.getText().toString().isEmpty())
            {
                Log.e("empty","empty");                 
                <EditText>.setFilters(new InputFilter[]{filter, new InputFilter.LengthFilter(2)});              
            }
            else if (<EditText>.getText().toString().charAt(0) >= "6".charAt(0))
            {
                Log.e("front num bad","greater than 5");
                <EditText>.setFilters(new InputFilter[]{filter, new InputFilter.LengthFilter(2)});
            }
            else 
            {
                Log.e("unfiltered", "unfiltered");
                <EditText>.setFilters(new InputFilter[]{new InputFilter.LengthFilter(2)});      
            }
            if (kicker)
            {
                return null;
            }
        }           
    }       
}

Then, within the onCreate method:

    Time_sec.setOnFocusChangeListener(new OnFocusChangeListener() 
    {
        public void onFocusChange(View v, boolean hasFocus)
        {
            new FilterCheckerTask().execute();
            if(!hasFocus)
                    {kicker = !hasFocus;}                               

        }
    });

As I said in the first part, this will make it so the user can only input numbers between 00 and 59 in your edittext box. I know it may look a little sloppy, and it can probably be cleaned up a bit in some of the if statements, but as far as I can tell it works absolutely perfectly, and doesn't seem to slow the system at all. Hope this helps you, and if not, the future googlers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM