点按外部EditText失去焦点 [英] Tap outside edittext to lose focus

查看:738
本文介绍了点按外部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失去焦点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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