0

what i'm trying to do sounds really simple. Resize my GridView when SoftKeyboard is open. Put it back on place(resize height) where it belongs if SoftKeyboard dissapears.

For this i did following:

root.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

        @Override
        public void onGlobalLayout() {
            // TODO Auto-generated method stub
            if(gv != null && searchbar != null) {
                root.getWindowVisibleDisplayFrame(r);
                if(screenHeight > r.bottom) {
                    RelativeLayout.LayoutParams myLayoutParams = (android.widget.RelativeLayout.LayoutParams) gv.getLayoutParams();
                    myLayoutParams.removeRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
                    gv.setLayoutParams(myLayoutParams);
                    int gvHeight = screenHeight - r.bottom - searchbar.getLayoutParams().height;
                    gv.getLayoutParams().height = gvHeight;
                }else {
                    RelativeLayout.LayoutParams myLayoutParams = (android.widget.RelativeLayout.LayoutParams) gv.getLayoutParams();
                    myLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
                    gv.setLayoutParams(myLayoutParams);
                }

            }

        }
    });

Where gv is my GridView. If i start my app, and click in my searchbar, the softkeyboard appears and this method is firing all the time.(Even if the layout isn't changing or even that i don't click anything). Therefore it blocks my UI. Did i do something wrong?

Also, does someone have a better idea implementing this function.(Resizing my Grid when Softkeyboard appears and vice versa).

Any help is appreciated.

Notice

Working with onFocusChange sounds not good to me. Because on my device. I can Close the SoftKeyboard with a backPress without loosing Focus

MMike
  • 588
  • 3
  • 22

1 Answers1

0

Have you tried using View.OnLayoutChangeListener available for API 11+ instead?

Otherwise you have to remove the listener when it fires after checking for a large enough height difference (see this). Don't forget to add the listener back in any click listener that fires up the keyboard.

@Override
public void onGlobalLayout() {
    int heightDiff = root.getRootView().getHeight() - root.getHeight();
    if (heightDiff > 100) { // if more than 100 pixels, its probably a keyboard...
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            root.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        } else {
            root.getViewTreeObserver().removeGlobalOnLayoutListener(this);
        }
        ... rest of your code
    }
}
Community
  • 1
  • 1
Jasoneer
  • 2,060
  • 2
  • 13
  • 20
  • With increased device resolution, heightDiff > 100 doesn't work now. The number needs to be increased now. I have now set to > 200 – Gautam Jain Jun 15 '20 at 08:05