How to set windowsoftinputmode programmatically from Fragments?

Tarun picture Tarun · Oct 15, 2017 · Viewed 14.6k times · Source

I have a requirement in which I have one MainActivity. From this activity I instantiate 4 fragments(Let us say FragmentA, FragmentB, FragmentC, FragmentD.

Out of these four Fragments; on 3 Fragments(Let us say FragmentA, FragmentB, FragmentC), I want to set MainActivity's windowsoftinputmode() to SOFT_INPUT_ADJUST_PAN so that window can resize.

And on one Fragment()let us say FragmentD), I want to set MainActivity's windowsoftinputmode() to SOFT_INPUT_ADJUST_NOTHING.

So what I do is, on each Fragment's onViewCreated() method I execute the following line of code with changing LayoutParams flag:

((MainActivity)getActivity()).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);

or

((MainActivity)getActivity()).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

Problem is that it not working and I am not able to setSoftInputMode correctly and I can not prevent window getting resized.

Same lines of code works perfectly when I execute them in onCreate() of MainActivity as shown :

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

But than the value is set for all four fragments. My MainActivity declaration in manifest is :

<activity
    android:name="com.test.MainActivity"
    android:launchMode="singleTask"
    android:screenOrientation="portrait"/>

Can somebody help what I am doing wrong in this. I want to have behaviour different for different Fragments.

Answer

batsheva picture batsheva · Oct 15, 2017

try this I found :

aim to use two different modes for tabs. The modes are SOFT_INPUT_ADJUST_RESIZE and SOFT_INPUT_ADJUST_NOTHING.

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

The code line above simply doesn't work by itself. App always behaves in a state ADJUST_NOTHING. However, if windowSoftInputMode="adjustResize" is inserted into tag in AndroidManifest.xml file, app window is resized as default. Additionally, when you call following line in fragment

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

it will behave as expected and nothing is resized. worked by me!