Skip to content

Instantly share code, notes, and snippets.

@grennis
Created April 27, 2017 14:36
Show Gist options
  • Star 25 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save grennis/2e3cd5f7a9238c59861015ce0a7c5584 to your computer and use it in GitHub Desktop.
Save grennis/2e3cd5f7a9238c59861015ce0a7c5584 to your computer and use it in GitHub Desktop.
public class SoftInputAssist {
private View rootView;
private ViewGroup contentContainer;
private ViewTreeObserver viewTreeObserver;
private ViewTreeObserver.OnGlobalLayoutListener listener = () -> possiblyResizeChildOfContent();
private Rect contentAreaOfWindowBounds = new Rect();
private FrameLayout.LayoutParams rootViewLayout;
private int usableHeightPrevious = 0;
public SoftInputAssist(Activity activity) {
contentContainer = (ViewGroup) activity.findViewById(android.R.id.content);
rootView = contentContainer.getChildAt(0);
rootViewLayout = (FrameLayout.LayoutParams) rootView.getLayoutParams();
}
public void onPause() {
if (viewTreeObserver.isAlive()) {
viewTreeObserver.removeOnGlobalLayoutListener(listener);
}
}
public void onResume() {
if (viewTreeObserver == null || !viewTreeObserver.isAlive()) {
viewTreeObserver = rootView.getViewTreeObserver();
}
viewTreeObserver.addOnGlobalLayoutListener(listener);
}
public void onDestroy() {
rootView = null;
contentContainer = null;
viewTreeObserver = null;
}
private void possiblyResizeChildOfContent() {
contentContainer.getWindowVisibleDisplayFrame(contentAreaOfWindowBounds);
int usableHeightNow = contentAreaOfWindowBounds.height();
if (usableHeightNow != usableHeightPrevious) {
rootViewLayout.height = usableHeightNow;
rootView.layout(contentAreaOfWindowBounds.left, contentAreaOfWindowBounds.top, contentAreaOfWindowBounds.right, contentAreaOfWindowBounds.bottom);
rootView.requestLayout();
usableHeightPrevious = usableHeightNow;
}
}
}
@SANDY-9
Copy link

SANDY-9 commented Apr 1, 2023

thanks.

@Twodies
Copy link

Twodies commented May 3, 2023

Worked for me after I have replaced

int usableHeightNow = contentAreaOfWindowBounds.height();

with

int usableHeightNow = contentAreaOfWindowBounds.bottom;

otherwise I had a large gap at the bottom of the screen.

Thanks Bro it was a problem for me. But a little bit problem while launching the activity, splash like problem. If you found an answer please email me. twodiesdeveloper@gmail.com. I'll be waiting to your answer.

@benardelia
Copy link

Can this be used in fragment...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment