How to hide soft keyboard on android after clicking outside EditText?

前端 未结 30 2124
醉话见心
醉话见心 2020-11-22 11:46

Ok everyone knows that to hide a keyboard you need to implement:

InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hi         


        
30条回答
  •  旧时难觅i
    2020-11-22 12:27

    You can achieve this by doing the following steps:

    1. Make the parent view(content view of your activity) clickable and focusable by adding the following attributes

          android:clickable="true" 
          android:focusableInTouchMode="true" 
      
    2. Implement a hideKeyboard() method

          public void hideKeyboard(View view) {
              InputMethodManager inputMethodManager =(InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE);
              inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
          }
      
    3. Lastly, set the onFocusChangeListener of your edittext.

          edittext.setOnFocusChangeListener(new View.OnFocusChangeListener() {
              @Override
              public void onFocusChange(View v, boolean hasFocus) {
                  if (!hasFocus) {
                      hideKeyboard(v);
                  }
              }
          });
      

    As pointed out in one of the comments below, this might not work if the parent view is a ScrollView. For such case, the clickable and focusableInTouchMode may be added on the view directly under the ScrollView.

提交回复
热议问题