editText is not losing focus

只谈情不闲聊 提交于 2019-11-30 11:09:21
PPShein

It's simple. You can put the following in LinearLayout or any other else:

android:focusableInTouchMode="true"

Override Activity.dispatchTouchEvent():

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    if (ev.getAction() == MotionEvent.ACTION_DOWN) {
        View view = getCurrentFocus();
        if (view != null && view instanceof EditText) {
            Rect r = new Rect();
            view.getGlobalVisibleRect(r);
            int rawX = (int)ev.getRawX();
            int rawY = (int)ev.getRawY();
            if (!r.contains(rawX, rawY)) {
                view.clearFocus();
            }
        }
    }
    return super.dispatchTouchEvent(ev);
}

That way, whenever someone clicks anywhere, you have control, and it's at only one point in code.

Create an onClick listener, possibly in your XML layout to listen for clicks in the background LinearLayout. From here you can call .clearFocus() on your EditText after you make it an instance variable of the activity you are working in.

Amrit

You can remove the focus from the EditText, by setting the focus to other field by calling the method.

Suppose I have set the focus to back button on click of done button, then call the method on back button inside done button click listener.

And your problem is solved.

back.requestFocusFromTouch();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!