Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide Soft Keyboard In Android App From ViewPager Fragments

I have an Android app that contains a ViewPager with 2 fragments. The first fragment contains an EditText field. When the app launches, that field immediately takes focus and the soft keyboard is launched (which I want to happen). The second fragment only contains a list (no editable text fields). When I swipe from fragment 1 to fragment 2, I'd like the keyboard to go away. Nothing I've tried seems to work. The keyboard not only remains in view, it continues to update fragment 1's EditText field.

I figure I'm either using incorrect code to hide the keyboard or placing it in an incorrect location. If anyone can post an example of the correct implementation it would be greatly appreciated!

My latest attempt was to place code that should hide the keyboard in fragment 1's onDetach() method:

@Override
public void onDetach()
{
    super.onDetach();

    InputMethodManager imm = (InputMethodManager) this.context.getSystemService(Context.INPUT_METHOD_SERVICE);

    // I'VE TRIED ALL THREE BELOW, NONE OF THEM WORK...

        // imm.hideSoftInputFromWindow(this.messageView.getWindowToken(), 0);
        // imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
        // this.context.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
like image 568
Jabari Avatar asked Aug 28 '12 20:08

Jabari


1 Answers

See this answer. Basically, you need to have your ViewPager's OnPageChangeListener hide the keyboard for you. (If you want your swiping animation to remain smooth, do this in onPageScrollStateChanged instead of onPageSelected.)

@Override
public void onPageScrollStateChanged(int state)
{
    if (state == ViewPager.SCROLL_STATE_IDLE)
    {
        if (mViewPager.getCurrentItem() == 0)
        {
            // Hide the keyboard.
            ((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE))
                .hideSoftInputFromWindow(mViewPager.getWindowToken(), 0);
        }
    }
}
like image 131
Makario Avatar answered Nov 17 '22 23:11

Makario