点击外部edittext失去焦点

Tap outside edittext to lose focus(点击外部edittext失去焦点)
本文介绍了点击外部edittext失去焦点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我只想在edittext"外部单击时自动失去焦点并隐藏键盘.目前,如果我点击edittext"它会聚焦,但我需要点击后退按钮才能取消聚焦.

I just want when click outside the "edittext" to automatically lose focus and hide keyboard. At the moment, if I click on the "edittext" it focuses but i need to hit the back button to unfocus.

推荐答案

要解决这个问题,首先要使用 Edittext 的 setOnFocusChangeListener

To solve this problem what you have to do is first use setOnFocusChangeListener of that Edittext

edittext.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    Log.d("focus", "focus lost");
                    // Do whatever you want here
                } else {
                    Log.d("focus", "focused");
                }
            }
        });

然后您需要做的是在包含 Edittext 的活动中覆盖 dispatchTouchEvent,请参见下面的代码

and then what you need to do is override dispatchTouchEvent in the activity which contains that Edittext see below code

@Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if ( v instanceof EditText) {
                Rect outRect = new Rect();
                v.getGlobalVisibleRect(outRect);
                if (!outRect.contains((int)event.getRawX(), (int)event.getRawY())) {
                    Log.d("focus", "touchevent");
                    v.clearFocus();
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
        }
        return super.dispatchTouchEvent(event);
    }

现在会发生什么,当用户点击外部时,首先会调用这个 dispatchTouchEvent,然后从 editext 清除焦点,现在你的 OnFocusChangeListener 将被调用,焦点已经改变,现在你可以做任何你想做的事情想做,希望有效:)

Now what will happen is when a user click outside then, firstly this dispatchTouchEvent will get called which then will clear focus from the editext, now your OnFocusChangeListener will get called that focus has been changed, now here you can do anything which you wanted to do, hope it works :)

这篇关于点击外部edittext失去焦点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Change the style of AlertDialog(更改 AlertDialog 的样式)
Pop up dialog in Android home screen(在 Android 主屏幕中弹出对话框)
How to display an existing ListFragment in a DialogFragment(如何在 DialogFragment 中显示现有的 ListFragment)
When to use Android PopupWindow vs Dialog(何时使用 Android PopupWindow vs Dialog)
Android: Close dialog window on touch(Android:触摸时关闭对话框窗口)
Android - Executing a custom listview in a custom dialog properly(Android - 在自定义对话框中正确执行自定义列表视图)