Reputation: 465
I have ViewPager, and it shows fragments, one of them contains edittext. When user clicks on edittext and then swipes to another page, keyboard hides half of a screen. How can I hide keyboard, when page is changed? I tried something like this, but it doesn't work:
mFragmentsViewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
@Override
public Fragment getItem(int position) {
InputMethodManager inputManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(floatingActionButton.getWindowToken(), 0);
switch (position){
case 0:
return mFragments.get(0);
case 1:
return mFragments.get(1);
case 2:
return mFragments.get(2);
default:
return mFragments.get(0);
}
}
@Override
public int getCount() {
return 3;
}
});
Thanks everyone for answers in advance!
Upvotes: 4
Views: 1120
Reputation: 1
Maybe this will help someone, using viewPager2. This worked for me.
ViewPager2.OnPageChangeCallback() {
@Override
public void onPageSelected(int position) {
super.onPageSelected(position);
hideKeyboard();
}
});
//the method hideKeyboad()
private void hideKeyboard() {
InputMethodManager imm = (InputMethodManager) requireContext().getSystemService(Activity.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(viewPager2.getWindowToken(), 0);
}
}
Upvotes: 0
Reputation: 106
Instead of having the adapter take care of the keyboard I recommend you add a OnPageChangeListener type listener to the ViewPager and adding the code on the onPageSelected method:
mFragmentsViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getWindow().getCurrentFocus().getWindowToken(), 0);
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
}
Hopefully this helps!
Upvotes: 3
Reputation: 1335
make a general function like this and you can reuse it where-ever required
public static void hideSoftKeyboard(Activity activity) {
try {
InputMethodManager inputMethodManager =
(InputMethodManager) activity.getSystemService(
Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(
activity.getCurrentFocus().getWindowToken(), 0);
//inputMethodManager.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
}
catch (Exception e)
{
e.printStackTrace();
}
}
Upvotes: 1