Android輸入框被遮擋工具類

首先需要添加一句:

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

然後調用工具類:

.assistActivity(Activity activity);

public class MyWorkGround{

public static void assistActivity(Activity activity) {
    new AndroidBug5497Workaround(activity);
}
private View mChildOfContent;
/*保存改變高度前的高度*/
private int usableHeightPrevious;
private FrameLayout.LayoutParams frameLayoutParams;
private Activity activity;
private AndroidBug5497Workaround(final Activity activity) {
    this.activity = activity;
    FrameLayout content = (FrameLayout) activity.findViewById(android.R.id.content);
    mChildOfContent = content.getChildAt(0);
    //整體佈局監聽:當軟鍵盤打開,關閉,虛擬鍵盤顯示,隱藏時都會調用該方法
    mChildOfContent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        public void onGlobalLayout() {
            possiblyResizeChildOfContent();
        }
    });
    frameLayoutParams = (FrameLayout.LayoutParams) mChildOfContent.getLayoutParams();
}

private void possiblyResizeChildOfContent() {
    //activity有效高度
    int usableHeightNow = computeUsableHeight();
    //有效高度與之前的有效高度不等時,則重新設置高度
    if (usableHeightNow != usableHeightPrevious) {
        //可能是因爲用了沉浸式,所以在有效高度上需要加上狀態欄的高度
        //如果你發現這樣寫高度不對,可以去掉狀態欄高度試試
        frameLayoutParams.height = usableHeightNow + getStatusHeight(activity);
        mChildOfContent.requestLayout();
        //保存本次有效高度
        usableHeightPrevious = usableHeightNow;
    }
}

private int computeUsableHeight() {
    Rect r = new Rect();
    mChildOfContent.getWindowVisibleDisplayFrame(r);
    return r.bottom - r.top;// 全屏模式下: return r.bottom
}
/**
 * 獲得狀態欄的高度
 *
 * @param context
 * @return
 */
public static int getStatusHeight(Context context)
{

    int statusHeight = -1;
    try
    {
        Class<?> clazz = Class.forName("com.android.internal.R$dimen");
        Object object = clazz.newInstance();
        int height = Integer.parseInt(clazz.getField("status_bar_height")
                .get(object).toString());
        statusHeight = context.getResources().getDimensionPixelSize(height);
    } catch (Exception e)
    {
        e.printStackTrace();
    }
    return statusHeight;
}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章