Programmatically Hide Soft Keyboard in ViewPager.OnPageChangeListener onPageSelected()?

snotyak picture snotyak · Aug 5, 2012 · Viewed 17.7k times · Source

I have a ViewPager + ActionBar with tabs. I want to make the soft keyboard hide when I "swipe" to another tab but I can't figure out how.

I've passed in my Activity to the constructor for the FragmentPageAdapter so I can call

 activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

But it doesn't do anything (and it is in a reachable area of the code)...help?

Answer

almalkawi picture almalkawi · Aug 5, 2012

In your activity, you can do the following:

mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
    @Override
    public void onPageSelected(int position) {
        final InputMethodManager imm = (InputMethodManager)getSystemService(
            Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(mView.getWindowToken(), 0);
    }

    @Override
    public void onPageScrolled(int position, float offset, int offsetPixels) {
    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }
});