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

前端 未结 30 2373
醉话见心
醉话见心 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条回答
  •  面向向阳花
    2020-11-22 12:24

    Plea: I recognize I have no clout, but please take my answer seriously.

    Problem: Dismiss soft keyboard when clicking away from keyboard or edit text with minimal code.

    Solution: External library known as Butterknife.

    One Line Solution:

    @OnClick(R.id.activity_signup_layout) public void closeKeyboard() { ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); }
    

    More Readable Solution:

    @OnClick(R.id.activity_signup_layout) 
    public void closeKeyboard() {
            InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
    }
    

    Explanation: Bind OnClick Listener to the activity's XML Layout parent ID, so that any click on the layout (not on the edit text or keyboard) will run that snippet of code which will hide the keyboard.

    Example: If your layout file is R.layout.my_layout and your layout id is R.id.my_layout_id, then your Butterknife bind call should look like:

    (@OnClick(R.id.my_layout_id) 
    public void yourMethod {
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
    }
    

    Butterknife Documentation Link: http://jakewharton.github.io/butterknife/

    Plug: Butterknife will revolutionize your android development. Consider it.

    Note: The same result can be achieved without the use of external library Butterknife. Just set an OnClickListener to the parent layout as described above.

提交回复
热议问题