Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Limit EditText to Integer input only

Tags:

java

android

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);
like image 975
Somk Avatar asked Oct 07 '22 22:10

Somk


1 Answers

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".
like image 112
Arun Chettoor Avatar answered Oct 12 '22 12:10

Arun Chettoor