android - 如何避免单击按钮时调用 dispatchTouchEvent

标签 android android-softkeyboard android-button touch-event

在我的 Activity 中,我有一个 EditText 和一个 Button。我覆盖了 dispatchTouchEvent 以在单击屏幕的其他区域而不是 EditText 时隐藏软键盘。

@Override
public boolean dispatchTouchEvent(MotionEvent event) {
    View view = getCurrentFocus();
    boolean ret = super.dispatchTouchEvent(event);

    if (view instanceof EditText) {
        View w = getCurrentFocus();
        int scrcoords[] = new int[2];
        w.getLocationOnScreen(scrcoords);
        float x = event.getRawX() + w.getLeft() - scrcoords[0];
        float y = event.getRawY() + w.getTop() - scrcoords[1];

        if (event.getAction() == MotionEvent.ACTION_UP
                && (x < w.getLeft() || x >= w.getRight() || y < w.getTop() || y > w
                        .getBottom())) {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(getWindow().getCurrentFocus()
                    .getWindowToken(), 0);
        }
    }
    return ret;
}

问题是,每次我点击Button,都会调用dispatchTouchEvent,所以软键盘会消失,这不是我想要的。我不想在单击 Button 时隐藏键盘。我在想是否可以在单击 Button 时避免调用 dispatchTouchEvent

我们将不胜感激任何反馈。

最佳答案

您不需要覆盖 dispatchTouch 事件。只需将您 Activity 的 onClickListener 设置为与 Button 和 EditText 相同,然后调用这些方法以在 switch case 的“默认”情况下隐藏软键盘。

switch (v.getId())
    {
        case R.id.button:
            whateverButtonDoes();
            break;
        case R.id.editText:
            whateverEditTextDoes();
            break;
        default:
            hideKeyboard();
            break;
    }

我强烈建议您定义一种方法来隐藏键盘以实现清晰的编码标准。您也可以在其他地方使用它。

关于android - 如何避免单击按钮时调用 dispatchTouchEvent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27948059/

相关文章:

android - 三个按钮中只有一个起作用

android - 处理在不同 Activity 中收到的 gcm 推送通知?

android - 设置 android 系统范围的代理设置

android - 无法使用 Espresso 启动应用程序

Android - 在键盘上方显示 BottomSheetDialogFragment

android - 软键盘不隐藏

android - 图像+文本在按钮中居中对齐

android - 具有可检查实现的 FloatingActionButton

android - 横向显示 SoftKeyboard 但不是整个屏幕

Android:如何获取默认应用样式?