Hide soft keyboard on losing focus

后端 未结 9 1289
-上瘾入骨i
-上瘾入骨i 2020-12-04 16:47

When we have an EditText and it loses focus (to an element that doesn\'t need a keyboard), should the soft keyboard hide automatically or are we supposed to hid

9条回答
  •  忘掉有多难
    2020-12-04 17:12

    Best way is to set a OnFocusChangeListener for the EditText, and then add the code to the the keyboard into the OnFocusChange method of the listener. Android will then automatically close the keyboard when the EditText loses focus.

    Something like this in your OnCreate method:

    EditText editText = (EditText) findViewById(R.id.textbox);
    OnFocusChangeListener ofcListener = new MyFocusChangeListener();
    editText.setOnFocusChangeListener(ofcListener);
    

    and then add the class:

    private class MyFocusChangeListener implements OnFocusChangeListener {
    
        public void onFocusChange(View v, boolean hasFocus){
    
            if(v.getId() == R.id.textbox && !hasFocus) {
    
                InputMethodManager imm =  (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
    
            }
        }
    }
    

提交回复
热议问题