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.