Jabari
Jabari

Reputation: 5519

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);
}

Upvotes: 9

Views: 3715

Answers (3)

user2488738
user2488738

Reputation: 21

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

Upvotes: 0

Makario
Makario

Reputation: 2117

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);
        }
    }
}

Upvotes: 12

ClarkXP
ClarkXP

Reputation: 1233

In your AndroidManifest you should add to Activity declaration android:windowSoftInputMode="stateHidden":

<activity 
        android:name="YourActivity"            
        android:windowSoftInputMode="stateHidden">           
</activity>

And in your layout delete from EditText's children requestFocus:

<EditText
    android:id="@+id/editText1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_marginLeft="15dp"
    android:ems="10" >
    <requestFocus />
</EditText>

Upvotes: 0

Related Questions