Move your layout up to a certain View when Keyboard is showing [Android]

Claus Chierici
Karlmax Berlin
Published in
2 min readJun 10, 2021

When the keyboard opens up it consumes its space on the screen and overlaps the UI of your app.

To avoid that the corresponding input field is also overlapped you can simply add

<activity
...
android:windowSoftInputMode=”adjustResize” />

to the Manifest.xml. So the apps UI always moves up to the input field that just got the focus.

So far so good, but what if you need to have some more of your screen to be visible while the keyboard is opened? E.g. you have a text field below your input field that gives some important information or feedback on that data to be typed in the input field.

Well, one solution to achieve this is to put everything inside a ScrollView and just scroll up to the required position when the keyboard appears.

1. Detect keyboard is open

A good place to check if a keyboard is open or not is the

ViewTreeObserver.OnGlobalLayoutListener

resp. its callback

onGlobalLayout()

which is always called when the layout state of your current view tree has changed or any visibility changes happened.

You need to register your OnGlobalLayoutListener in onResume() and unregister in onPause().

On how to check if the keyboard has opened please refer to the following article. You’ll find code snippets for some extension functions there:

(Thanks to the author).

2. Scroll to the wanted position

After applying the code snippets from the article above you can implement your OnGlobalLayoutListener as follows (given that you do this in a Fragment):

Note that MyScrollView and MyVisibleView should be the references to your views. Yes, the ones you retrieved by findViewByID() in the distant past.
If you use view binding in the meantime this could look like this:

To round this up you can add a bottom padding to the ScrollView of your layout so there is a bit space between the keyboard and MyVisibleView.
Note that adding the padding to the view itself will have no effect here.
If you want to have a 200ms delay, or more, or less is entirely up to your taste.

--

--

Claus Chierici
Karlmax Berlin

Senior Android Developer and Tech Lead @ KarlmaxBerlin, Illuminator & DJ @ antamauna soundlab