场景: 在弹出的评论列表底部有一个输入框,当键盘弹出的时候输入框会被键盘遮挡一部分
想要实现: 输入框整体被键盘顶起不要被遮挡
代码: 通过监听根 View 的变化 并根据键盘的高度将布局上移
android:windowSoftInputMode="adjustPan"
mFragmentView.getViewTreeObserver().addOnGlobalLayoutListener(mOnGlobalLayoutListener);
private ViewTreeObserver.OnGlobalLayoutListener mOnGlobalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
possiblyResizeChildOfContent();
}
};
private int mUsableHeightPrevious;
private void possiblyResizeChildOfContent() {
int usableHeightNow = computeUsableHeight();
int heightDifference;
if (usableHeightNow != mUsableHeightPrevious) {
int usableHeightSansKeyboard = mFragmentView.getRootView().getHeight();
heightDifference = usableHeightSansKeyboard - usableHeightNow;
if (heightDifference > 200) {
// keyboard probably just became visible
mFragmentView.setPadding(0, 0, 0, heightDifference);
} else {
// keyboard probably just became hidden
mFragmentView.setPadding(0, 0, 0, 0);
}
mUsableHeightPrevious = usableHeightNow;
}
}
private int computeUsableHeight() {
final Rect rect = new Rect();
mFragmentView.getWindowVisibleDisplayFrame(rect);
return rect.bottom - rect.top;
}