Setting windowSoftInputMode for a single fragment

Paolo Montalto
2 min readJul 30, 2018

Every android developer knows that he/she can set windowSoftInputMode inside AndroidManifest.xml as an attribute for each activity to manage the behaviour related to the software keyboard.

You may know that it’s pretty simple to do so at runtime by calling the

activity?.window?.setSoftInputMode(mode)

method on an activity instance.

But what if you need to change the soft input mode in just the current fragment and not the whole activity?

You may wonder why you would do so: just imagine that you implemented a single activity navigation model and you need some fragments to behave differently from the rest of the app.

What would you want to do is tipically:

  • save the current softInputMode somewhere
  • set the new softInputMode when your fragment is created
  • restore the old softInputMode when the fragment is destroyed

In doing so, you will notice that while a setSoftInputMode method is available on the Window object, we don’t have a getter method as well.

With a little effort you will find that current softInputMode can be accessed by getting it from the window’s attributes manully, like this:

activity?.window?.attributes?.softInputMode

What I did for my apps is to create a convenience extension method on the Window object

--

--

Paolo Montalto
Paolo Montalto

Written by Paolo Montalto

Android Engineer, freelance, mobile developer, software craftsman, guitar strummer, husband, father, humble.

Responses (5)