androidandroid-edittextandroid-softkeyboardcustom-keyboardandroid-inputtype

Hide Android soft keyboard and only allow digits on EditText


I have a custom keyboard and don't want to show the Android softkeyboard. this can be achieved by the following code (How to hide Android soft keyboard on EditText):

editText.setInputType(InputType.TYPE_NULL);

However the EditText should only allow digits. this can be achieved by:

editText.setInputType(InputType.TYPE_CLASS_NUMBER);

I can't seem to find a way to combine both functionalities. setting the inputtype to TYPE_NULL will allow non-numeric characters when using hardware keyboards and setting the inputtype to TYPE_CLASS_NUMBER causes the soft keyboard to pop up.


Solution

  • The answer from airowe guided me in the right direction. This solution didn't seem to work for Android 2.3.X devices (the soft keyboard would still pop up). So I tweaked it a bit. I ended up using the following code:

    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(editText.getWindowToken(), 0); //hide keyboard
    
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
    {
       editText.setInputType(InputType.TYPE_CLASS_NUMBER);
    }
    else
    {
       editText.setRawInputType(InputType.TYPE_NULL);
    }
    

    This would probably allow pre-honeycomb tablets to enter text. However I think this is negligible.