Search code examples
androidandroid-softkeyboardmotionevent

How to detect a MotionEvent inside dispatchTouchEvent


I have made a FragmentActivity. Some Fragments include an EditText.

I would like, when the Soft Input Keyboard is up and a MotionEvent happens - except the Event of clicking inside the EditText - the Soft Input to hide. Until now I wrote this code in my MainActivity:

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {

    InputMethodManager im = (InputMethodManager) getApplicationContext()
                                  .getSystemService(Context.INPUT_METHOD_SERVICE);
    im.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(),
                                   InputMethodManager.HIDE_NOT_ALWAYS);
    return super.dispatchTouchEvent(ev);
}

It seems to work. But when I click inside the EditText, it hides and it comes up again. I wouldn't like this to happen. In this case I want the Keyboard just to remain on the screen.

  1. Is there any way to disable somehow the dispatchTouchEvent() when I click at an EditText inside of a Fragment?

  2. Is there any way to detect the click event of an EditText inside of dispatchTouchEvent() and make a condition there, that disables the hiding of the soft input?


Solution

  • Since dispatchTouchEvent() is the first method called when a touch happens on a screen , you need to find whether the touch falls within the bound of your edit text view. You can get the touch point as, int x = ev.getRawX(); int y = ev.getRawY();

    method to check whether it falls within the bounds of editText

    boolean isWithinEditTextBounds(int xPoint, int yPoint) {
        int[] l = new int[2];
        editText.getLocationOnScreen(l);
        int x = l[0];
        int y = l[1];
        int w = editText.getWidth();
        int h = editText.getHeight();
    
        if (xPoint< x || xPoint> x + w || yPoint< y || yPoint> y + h) {
            return false;
        }
        return true;
    } 
    

    In your onDispatchTouch() do.

    if(isWithinEditTextBounds(ev.getRawX,ev.getRawY))
    {
    //dont hide keyboard
    } else {
    //hide keyboard
    }