在Android中在EditText之外单击时关闭键盘 [英] Dismiss keyboard when click outside of EditText in android

查看:688
本文介绍了在Android中在EditText之外单击时关闭键盘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an EditText called myTextview. I want the soft keyboard to show when I click on the EditText but then dismiss if I click outside of the EditText. So I use the method below. But the keyboard does not dismiss when I click outside the view (I click a TextView). How do I fix this code?

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

        }
    });

推荐答案

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

I found a better solution:

覆盖活动"中的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.

This is applicable even if you are working with webview.

更新2020年7月10日

上述方法可以正常工作,但是EditText仍然具有焦点,并且键入光标仍然可见.

The above method works perfectly but the EditText is still has the focus and typing cursor is still visible.

解决上述问题.这样做

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

  1. Add findViewById(android.R.id.content).setFocusableInTouchMode(true); in your onCreate() method

hideKeyboard()方法

贷记到 Eddwhis的评论

这篇关于在Android中在EditText之外单击时关闭键盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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