Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android ViewPager show soft keyboard in the wrong place

I use a ViewPager with 3 fragment. The first one have only text. The second, a input field. the third, only text.

When the ViewPager is initialized, the soft keyboard is show, because the focus is set the the input field. If I change the order of fragment, the soft keyboard is not shown.

How I can control the focus et soft keyboard with ViewPager ?

Regards

like image 958
pprados Avatar asked Feb 03 '12 12:02

pprados


2 Answers

The best solution I've found so far is to use android:windowSoftInputMode="stateHidden" in your activity's manifest, and then add this to your activity.

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

I didn't use onPageSelected() because the hide-keyboard animation screws with the swiping animation. And I didn't use the android:focusable trick because the keyboard isn't hidden when you swipe back to an input-less fragment. Although I suppose you could combine that with the above code.

like image 187
Timmmm Avatar answered Sep 27 '22 19:09

Timmmm


I'm sure there is a better way to do this, but I was having the same problem and I got around it by setting the parent View to focusable. That way, whatever is causing the soft keyboard from popping up will not receive focus when you swipe between pages...

<!-- Dummy item to prevent your View from receiving focus -->
<LinearLayout
    ...
    android:focusable="true" 
    android:focusableInTouchMode="true" />

    <!-- The view(s) that are causing the keyboard to pop up each time you swipe -->
    <EditText ... />

</LinearLayout>
like image 36
Alex Lockwood Avatar answered Sep 27 '22 19:09

Alex Lockwood