Karlmax Berlin
Published in

Karlmax Berlin

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

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.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store