Tap outside edittext to lose focus

后端 未结 9 1745
萌比男神i
萌比男神i 2020-12-24 02:02

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

9条回答
  •  我在风中等你
    2020-12-24 02:52

    So I searched around a little bit, and no other solutions was exactly what I was looking for. In my opinion the focus behave strangely on EditText views.

    What I did was...

    1. Make sure the root view is a RelativeLayout

    2. Add an overlay layout that is OVER the area that will make the keyboard disapear, but not the EditText. Something like below:

    In my case, the EditText was in a container at the bottom of the screen. so it covered everyhting else.

    1. Have a method that looks a bit like this one :
        private void hideKeyboard() {
            final InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
            keyboardOverlay.setVisibility(View.GONE);
            editText.clearFocus();
        }
    
    1. Now call this method on the onClick of the overlay you created.

    2. What we want now is to make the overlay visible when you press on the editText. You cannot use the onFocus event (at least I did not get it to work...) So what i did is I managed the onTouch event instead.

    editText.setOnTouchListener(new OnTouchListener() {
    
        @Override
        public boolean onTouch(final View v, final MotionEvent event) {
            keyboardOverlay.setVisibility(View.VISIBLE);
            editText.requestFocus();
            return false;
        }
    });
    

    The requestFocus() here is to not override the focus event with the onTouch.

    Quick advice, when you try this out, you can add a background color to the overlay to see exactly what is happening.

    Hope it works for you!

提交回复
热议问题