7

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

Morgan Koh
  • 2,297
  • 24
  • 24
Mehul Gajjar
  • 431
  • 5
  • 20

3 Answers3

1

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();
        }
    }
Nitesh Pareek
  • 362
  • 2
  • 10
0

You can also do like this

getWindow().setSoftInputMode(
    WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN
);

Hope it help!

Saurabh Vardani
  • 1,821
  • 2
  • 18
  • 33
0

In case of Fragment use below code

View view = inflater.inflate(R.layout.fragment_test, container, false);

    view.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {

                if(event.getAction() == MotionEvent.ACTION_MOVE){
                    dispatchTouchEvent(event);
                }
                return true;
            }
    });

//here the rest of your code

return view;

Apply this code and call dispatchTouchEvent(); method

Nitesh Pareek
  • 362
  • 2
  • 10