android - 在Android中单击EditText外部时关闭键盘

标签 android android-layout

我有一个名为 myTextviewEditText。我希望软键盘在我单击 EditText 时显示,但如果我在 EditText 之外单击则关闭。所以我使用下面的方法。但是当我在 View 外部单击时键盘不会关闭(我单击 TextView)。如何修复此代码?

myTextview.setOnFocusChangeListener(new OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
                getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
            } else {
                InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(myTextview.getWindowToken(), 0);
            }

        }
    });

最佳答案

我找到了更好的解决方案:

覆盖 Activity 中的 dispatchTouchEvent 方法。

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    View v = getCurrentFocus();

    if (v != null && (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_MOVE) &&
            v instanceof EditText &&
            !v.getClass().getName().startsWith("android.webkit.")) {
        int[] sourceCoordinates = new int[2];
        v.getLocationOnScreen(sourceCoordinates);
        float x = ev.getRawX() + v.getLeft() - sourceCoordinates[0];
        float y = ev.getRawY() + v.getTop() - sourceCoordinates[1];

        if (x < v.getLeft() || x > v.getRight() || y < v.getTop() || y > v.getBottom()) {
            hideKeyboard(this);
        }

    }
    return super.dispatchTouchEvent(ev);
}

private void hideKeyboard(Activity activity) {
    if (activity != null && activity.getWindow() != null) {
        activity.getWindow().getDecorView();
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(activity.getWindow().getDecorView().getWindowToken(), 0);
        }
    }
}

即使您正在使用 webview,这也适用。

2020 年 7 月 10 日更新

上述方法效果很好,但 EditText 仍然有焦点,打字光标仍然可见。

解决上述问题。这样做

  1. 添加 findViewById(android.R.id.content).setFocusableInTouchMode(true); 在你的 onCreate() 方法中

  2. 添加 findViewById(android.R.id.content).clearFocus();hideKeyboard() 方法

归功于 Eddwhis's comment

关于android - 在Android中单击EditText外部时关闭键盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20713273/

相关文章:

android - 字符串错误 "constant string too long"

android - 执行 http POST 返回 HTML 而不是 JSON

java - 如何在 GridView 中使项目透明

android - 迁移到 Jetpack/AndroidX 后出现 InflateException

android - Calabash 处理 "Complete action using"对话框

android - 适用于 Android 的 PayPal ClassicAPI SDK

android - 具有自定义形状的 DialogFragment

android - 如何以编程方式将内容添加到自定义 XML 布局?

Android:ListView 的边距/填充没有应用于页眉的边距?

android:drawableLeft margin 和/或 padding