Dismiss keyboard when click outside of EditText in android

后端 未结 9 922
旧时难觅i
旧时难觅i 2021-02-01 05:31

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

9条回答
  •  再見小時候
    2021-02-01 06:05

    This way, the keyboard will only disappear when you touch a view that can gain focus. I suggest you to do the following:

    Create a custom ViewGroup like this:

    public class TouchLayout extends LinearLayout {
    
        private OnInterceptTouchEventListener mListener;
    
        public TouchLayout(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        @Override
        public boolean onInterceptTouchEvent(MotionEvent event) {
            if(mListener != null) {
                return mListener.onInterceptTouchEvent(event);
            }
            return super.onInterceptTouchEvent(event);
        }
    
        public void setOnInterceptTouchEventListener(OnInterceptTouchEventListener listener) {
            mListener = listener;
        }
    
        public interface OnInterceptTouchEventListener {
            public boolean onInterceptTouchEvent(MotionEvent event);
        }
    }
    

    Then add the custom View as a root of your xml layout:

    
    
            
    

    And in your Activity you should do the following:

    final TouchLayout root = (TouchLayout) findViewById(R.id.root);
    final EditText text = (EditText) findViewById(R.id.text);
    final InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    
    root.setOnInterceptTouchEventListener(new OnInterceptTouchEventListener() {
    
        @Override
        public boolean onInterceptTouchEvent(MotionEvent event) {
            final View v = getCurrentFocus();
            if(v != null && v.equals(text)) {
                final int screenCords[] = new int[2];
                text.getLocationOnScreen(screenCords);
                final Rect textRect = new Rect(screenCords[0], screenCords[1], screenCords[0] + text.getWidth(), screenCords[1] + text.getHeight());
                if(!textRect.contains(event.getRawX(), event.getRawY() {
                    imm.hideSoftInputFromWindow(myTextview.getWindowToken(), 0);
                    // Optionally you can also do the following:
                    text.setCursorVisible(false);
                    text.clearFocus(); 
                }
            }
            return false;
        }
    };
    

提交回复
热议问题