Skip to content

Instantly share code, notes, and snippets.

@grennis
Created April 27, 2017 14:36
Show Gist options
  • Select an option

  • Save grennis/2e3cd5f7a9238c59861015ce0a7c5584 to your computer and use it in GitHub Desktop.

Select an option

Save grennis/2e3cd5f7a9238c59861015ce0a7c5584 to your computer and use it in GitHub Desktop.

Revisions

  1. grennis created this gist Apr 27, 2017.
    50 changes: 50 additions & 0 deletions SoftInputAssist.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,50 @@
    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;
    }
    }
    }