Hide soft keyboard in Android application from ViewPager fragments

I have an Android app that contains a ViewPager with 2 fragments. The first fragment contains the EditText field. When the application starts, this field immediately focuses and the soft keyboard launches (what I want to do). The second fragment contains only a list (no editable text fields). When I make my way from fragment 1 to fragment 2, I would like the keyboard to go away. Nothing I tried seems to work. The keyboard not only remains in sight, it continues to update the EditText field of fragment 1.

I believe that I am using the wrong code to hide the keyboard or put it in the wrong location. If someone can post an example of the correct implementation, we will be very grateful!

My last attempt was to put code that should hide the keyboard in the 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); } 
+8
android android-softkeyboard android-fragments android-viewpager
source share
3 answers

See this answer. Basically, you need your ViewPager OnPageChangeListener hide the keyboard for you. (If you want your spread animation to remain smooth, do it 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); } } } 
+10
source share

In AndroidManifest, you must add the android activity declaration android: windowSoftInputMode = "stateHidden":

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

And in your layout, remove requestFocus from EditText children:

 <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> 
0
source share
  getActivity().getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); 
0
source share

All Articles