Hidden keyboard in fragment when click Sliding menu Navigation
-
21-12-2019 - |
Question
I want to hidden keyboard of edittext in Fragment A using Sliding Menu when I click Menu. I try using:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
if(this.getCurrentFocus() != null && this.getCurrentFocus() instanceof EditText){
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
return true;
}
and
@Override
public void onDrawerClosed(View drawerView) {
// TODO Auto-generated method stub
super.onDrawerClosed(drawerView);
getWindow()
.setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
@Override
public void onDrawerOpened(View drawerView) {
// TODO Auto-generated method stub
super.onDrawerOpened(drawerView);
getWindow()
.setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
but all not working. Please help me. Thanks!
Solution
public static void hideKeyboardForFocusedView(Activity activity) {
InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
View view = activity.getCurrentFocus();
if (view != null) {
inputManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
This method hides keyboard for any EditText.
OTHER TIPS
Try this way in Fragment
InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getView().getWindowToken(), 0);
In Activity
InputMethodManager inputManager = (InputMethodManager) your_activity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
View view = your_activity.this.getCurrentFocus();
if (view != null) {
inputManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
Another way is trying to implement dispatchTouchEvent(....)
in your Activity
like
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
View view = getCurrentFocus();
boolean ret = super.dispatchTouchEvent(event);
if (view instanceof EditText) {
View w = getCurrentFocus();
int scrcoords[] = new int[2];
w.getLocationOnScreen(scrcoords);
float x = event.getRawX() + w.getLeft() - scrcoords[0];
float y = event.getRawY() + w.getTop() - scrcoords[1];
if (event.getAction() == MotionEvent.ACTION_UP && (x < w.getLeft() || x >= w.getRight() || y < w.getTop() || y > w.getBottom()) ) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getWindow().getCurrentFocus().getWindowToken(), 0);
}
}
return ret;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow