Android-Android 4.4输入框无法上顶

package com.gzjiequan.rescuewithyou.util;

import android.app.Activity;
import android.graphics.Rect;
import android.view.View;
import android.widget.FrameLayout;

/**
 * Android 4.4 键盘弹出高度测量
 *
 * @author pc
 */
public class AndroidBug5497Workaround {

    private int stateHeight;

    public static void assistActivity(Activity activity) {
        new AndroidBug5497Workaround(activity);
    }

    private View mChildOfContent;
    private int usableHeightPrevious;
    private FrameLayout.LayoutParams frameLayoutParams;

    private AndroidBug5497Workaround(Activity activity) {
        stateHeight = activity.getResources().getDimensionPixelSize(activity.getResources().getIdentifier("status_bar_height", "dimen", "android"));
        FrameLayout content = activity.findViewById(android.R.id.content);
        mChildOfContent = content.getChildAt(0);
        mChildOfContent.getViewTreeObserver().addOnGlobalLayoutListener(() -> possiblyResizeChildOfContent());
        frameLayoutParams = (FrameLayout.LayoutParams) mChildOfContent.getLayoutParams();
        
    }

    /**
     *  键盘高度:usableHeightSansKeyboard ,无键盘的高度/屏幕高度:usableHeightSansKeyboard  可视内容高度:usableHeightNow
     */
    private void possiblyResizeChildOfContent() {
        int usableHeightNow = computeUsableHeight();
        if (usableHeightNow != usableHeightPrevious) {
            int usableHeightSansKeyboard = mChildOfContent.getRootView().getHeight();
            int heightDifference = usableHeightSansKeyboard - usableHeightNow;
            LogUtil.d(this.getClass().getSimpleName(),"heightDifference:"+heightDifference+"  usableHeightSansKeyboard:"+usableHeightSansKeyboard+" usableHeightNow"+usableHeightNow);
            if (heightDifference > (usableHeightSansKeyboard / 4)) {
                frameLayoutParams.height = usableHeightSansKeyboard - heightDifference+stateHeight;
            } else {
                // 键盘隐藏
                frameLayoutParams.height = usableHeightSansKeyboard;
            }
            mChildOfContent.requestLayout();
            usableHeightPrevious = usableHeightNow;
        }
    }

    private int computeUsableHeight() {
        Rect r = new Rect();
        mChildOfContent.getWindowVisibleDisplayFrame(r);
        return (r.bottom - r.top);
    }

}

你可能感兴趣的:(Android-Android 4.4输入框无法上顶)