监听软键盘状态工具类:
public class SoftKeyboardHelper {
public static SoftKeyboardHelper getKeyboardStateObserver(Activity activity) {
return new SoftKeyboardHelper(activity);
}
private View mChildOfContent;
private int usableHeightPrevious;
private OnKeyboardVisibilityListener listener;
public void setKeyboardVisibilityListener(OnKeyboardVisibilityListener listener) {
this.listener = listener;
}
private SoftKeyboardHelper(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();
}
});
}
private void possiblyResizeChildOfContent() {
int usableHeightNow = computeUsableHeight();
if (usableHeightNow != usableHeightPrevious) {
int usableHeightSansKeyboard = mChildOfContent.getRootView().getHeight();
int heightDifference = usableHeightSansKeyboard - usableHeightNow;
if (heightDifference > (usableHeightSansKeyboard / 4)) {
if (listener != null) {
listener.onKeyboardShow();
}
} else {
if (listener != null) {
listener.onKeyboardHide();
}
}
usableHeightPrevious = usableHeightNow;
}
}
private int computeUsableHeight() {
Rect r = new Rect();
mChildOfContent.getWindowVisibleDisplayFrame(r);
return (r.bottom - r.top);// 全屏模式下: return r.bottom
}
public interface OnKeyboardVisibilityListener {
void onKeyboardShow();
void onKeyboardHide();
}
}
调用(弹出时将布局滑到底部以使输入框可见):
SoftKeyboardHelper.getKeyboardStateObserver(this).setKeyboardVisibilityListener(new SoftKeyboardHelper.OnKeyboardVisibilityListener() {
@Override
public void onKeyboardShow() {
//滚到到底部:
scrollView.fullScroll(ScrollView.FOCUS_DOWN);
//滚动到顶部:
//scrollView.fullScroll(ScrollView.FOCUS_UP);
}
@Override
public void onKeyboardHide() {
}
});