Search code examples
androidtouchandroid-softkeyboard

Hide Numeric Keyboard ONLY WHEN clicked outside any of the Edit Text


I have three different Edit Text with restriction of entering only numeric values, thus tapping on any one of the Edit Text opens NUMERIC KEYBOARD.

I tried to implement setOnFocusChangeListener for all Edit Text which ensures that when user tap anywhere outside any of the Edit Text hide the keyboard.

editText1.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (!hasFocus) {
            hideKeyboard(v);
        }
    }
});

editText2.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (!hasFocus) {
            hideKeyboard(v);
        }
    }
});

editText3.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (!hasFocus) {
            hideKeyboard(v);
        }
    }
});

And here is the implementation of 'hideKeyBoard'

public void hideKeyboard(View view) {
        InputMethodManager inputMethodManager =(InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

This works fine, however, when I change focus from one EditText to another EditText, keyboard hides. This behaviour might be frustrating for user.

How can I deal with it and avoid unnecessary hiding of keyboard.

P.S I need to ensure that keyboard is numeric not alphabetical in any case.


Solution

  • Thank you MarianoZorrila for correcting me on my approach to the problem.
    Here are the changes I performed to solve this problem.

    1. Gave an Id to my Relative Layout

      <RelativeLayout
      ...
      ...
      android:id="@+id/parent">
      
    2. Modifications to Java File

      View parent = findViewById(R.id.parent);
      parent.setOnFocusChangeListener(new View.OnFocusChangeListener() {
          @Override
          public void onFocusChange(View view, boolean hasFocus) {
              if(hasFocus){
                  hideKeyboard(view);
              }
          }
      });