1

I have a fragment containing an EditText for search input and a ListView. I've got the search part working, but now I want to close the keyboard when the user clicks the on the screen outside of the EditText. I'd also like to consume the click event (because it is a ListView, if I don't consume the click event the user may accidentally click on a ListView item they didn't want to open)

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

What I've tried so far:

  • Implement View.OnClickListener in the fragment and implement onClick as such:

    @Override
    public void onClick(View v) {
        System.out.println("onClick true");
        if (!(v instanceof EditText)) {
            InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.
                    INPUT_METHOD_SERVICE);
            if (getActivity().getCurrentFocus() != null) {
                imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
            }
        }
    }
    

This never seemed to post "onClick true" when I clicked.

  • Override onTouchEvent in the fragment's activity and implement onTouchEvent as such:

    @Override
    public boolean onTouchEvent(final MotionEvent event) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.
                INPUT_METHOD_SERVICE);
        if (getCurrentFocus() != null) {
            imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        }
        return true;
    }
    

Any help would be greatly appreciated. Thanks in advance.

nbokmans
  • 5,492
  • 4
  • 35
  • 59

1 Answers1

2

If I get you right you can try to use a OnFocusChangeListener:

yourEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            final InputMethodManager inputManager = (InputMethodManager) getAppContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            if (inputManager != null && !hasFocus) {
                inputManager.hideSoftInputFromWindow(currentFocusedView.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    });

This is just a sample, but maybe it points into the right direction.

Thomas R.
  • 7,988
  • 3
  • 30
  • 39