Home Ask Login Register

Developers Planet

Your answer is one click away!

Gary Klasen February 2016

Hide part of activity_main.xml if keyboard is open (Android)

I have the following activity_main.xml shown at bottom. There, a CoordinatorLayout and two LinearLayouts occur. The first LinearLayout1 has an EditText to input some text, with a button to send it. The second one has two other buttons.

If i click into the EditText, the keyboard shows up and makes everything in LinearLayout2 barely visible. So, i want to hide both buttons in last layout when keyboard is open.

I already found out to use android:windowSoftInputMode="stateHidden" may be the trick, but only in connection with activities in AndroidManifest.xml. I just want to use this inner the second linear layout. Already tried to use it there, but with no success.

In addition, i what to handle this in my xml and keep my MainActivity-code clean. Any possibilities for this?

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android">

        <Button android:id="@+id/button_send"/>




androidnoobdev February 2016

We had same issue in past so we have put some observable on full layout object try this and let me know

/*Hide button when keyboard is open*/
view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    public void onGlobalLayout() {
        Rect r = new Rect();

        int heightDiff = view.getRootView().getHeight() - (r.bottom - r.top);

        if (heightDiff > 244) { // if more than 100 pixels, its probably a keyboard...
            //ok now we know the keyboard is up...

        } else {
            //ok now we know the keyboard is down...


Post Status

Asked in February 2016
Viewed 2,901 times
Voted 12
Answered 1 times


Leave an answer

Quote of the day: live life