如何在dispatchTouchEvent中检测到MotionEvent [英] How to detect a MotionEvent inside dispatchTouchEvent

查看:113
本文介绍了如何在dispatchTouchEvent中检测到MotionEvent的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一个FragmentActivity.一些片段包含EditText.

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

我想当软输入键盘打开并且发生MotionEvent时-除了在EditText内单击的事件外-要隐藏的软输入.到目前为止,我在MainActivity中编写了以下代码:

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);
}

似乎可行.但是,当我在EditText内部单击时,它会隐藏并再次出现.我不希望发生这种情况.在这种情况下,我只希望键盘保留在屏幕上.

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. 单击片段内的EditText时,是否可以通过某种方式禁用dispatchTouchEvent()?

有什么方法可以检测到dispatchTouchEvent()内部EditText的click事件并在那里建立条件,从而禁止隐藏软输入?

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?

推荐答案

由于dispatchTouchEvent()是在屏幕上发生触摸时调用的第一个方法,因此您需要确定触摸是否在编辑文本视图的范围内. 您可以通过以下方式获得接触点: int x = ev.getRawX(); int y = ev.getRawY();

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();

检查方法是否在editText范围内的方法

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;
} 

在您的onDispatchTouch()中执行.

In your onDispatchTouch() do.

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

这篇关于如何在dispatchTouchEvent中检测到MotionEvent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆