How to detect a MotionEvent inside dispatchTouchEvent

时光毁灭记忆、已成空白 提交于 2019-12-25 09:36:59

问题


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?


回答1:


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
}


来源:https://stackoverflow.com/questions/20700286/how-to-detect-a-motionevent-inside-dispatchtouchevent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!