hide keyboard in fragment on outside click

2020-02-26 11:21发布

I have a fragment containing an EditText for input, but now I want to close the keyboard when the user clicks on the screen outside of the EditText.

I know how to do this in an activity, but it seems to be different for fragments.

i am calling this method on view.onTouchListener

public static void hideSoftKeyboard() {
InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);

inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
}

anyone have solution, thanks

7条回答
家丑人穷心不美
2楼-- · 2020-02-26 12:00

Use this method its works fine

public static void hideKeyBoardMethod(final Context con, final View view) {
        try {
            view.post(new Runnable() {
                @Override
                public void run() {
                    InputMethodManager imm = (InputMethodManager) con.getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
查看更多
登录 后发表回答