Skip to content
Advertisement

How to hide the soft keyboard inside a fragment?

I have a FragmentActivity using a ViewPager to serve several fragments. Each is a ListFragment with the following layout:

JavaScript

When starting the activity, the soft keyboard shows. To remedy this, I did the following inside the fragment:

JavaScript

I save the incoming ViewGroup container parameter from onCreateView as a way to access the window token for the main activity. This runs without error, but the keyboard doesn’t get hidden from the call to hideSoftInputFromWindow in onStart.

Originally, I tried using the inflated layout instead of container, i.e:

JavaScript

but this threw a NullPointerException, presumably because the fragment itself isn’t an activity and doesn’t have a unique window token?

Is there a way to hide the soft keyboard from within a fragment, or should I create a method in the FragmentActivity and call it from within the fragment?

Advertisement

Answer

As long as your Fragment creates a View, you can use the IBinder (window token) from that view after it has been attached. For example, you can override onActivityCreated in your Fragment:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement