Reputation: 431
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
Upvotes: 7
Views: 8780
Reputation: 362
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
Upvotes: 0
Reputation: 1861
You can also do like this
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN
);
Hope it help!
Upvotes: 0
Reputation: 362
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();
}
}
Upvotes: 1