How to detect a MotionEvent inside dispatchTouchEvent
Asked Answered
A

1

0

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?

Ase answered 20/12, 2013 at 9:28 Comment(0)
A
9

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
}
Analgesia answered 20/12, 2013 at 10:11 Comment(2)
Is there another way without including getting raw points? For example, if the Object, that was clicked is an Instance of Edittext, do not hide the keyboard.Ase
A touch event is interpreted by android as follows Activity.dispatchTouchEvent() -> ViewGroup.dispatchTouchEvent->View.dispatchTouchEvent->View.onTouchListener.. so Activity.dispatchTouchevent() is always called first, after that only we can know about the view which received the touch event.Analgesia

© 2022 - 2024 — McMap. All rights reserved.