软键盘这块的代码在framework层,正常是无法获取的,但是可以软键盘弹起与关闭时,会触发GlobalLayoutListener
可由此实现监听。
public class KeyBoardStateUtil {
private OnKeyBoardStateListener mListener;
private View mRootLayout;
private int mVisibleHeight, mFirstVisibleHeight;
private boolean mIsKeyboardShow;
public KeyBoardStateUtil(Activity context) {
mRootLayout = ((ViewGroup) context.findViewById(android.R.id.content)).getChildAt(0);
calKeyBordState();
mRootLayout.getViewTreeObserver().addOnGlobalLayoutListener(mOnGlobalLayoutListener);
}
private ViewTreeObserver.OnGlobalLayoutListener mOnGlobalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
calKeyBordState();
}
};
public boolean keyboardShow() {
return mIsKeyboardShow;
}
private void calKeyBordState() {
if (mRootLayout == null) {
return;
}
Rect r = new Rect();
mRootLayout.getWindowVisibleDisplayFrame(r);
int visibleHeight = r.height();
if (mVisibleHeight == 0) {
mVisibleHeight = visibleHeight;
mFirstVisibleHeight = visibleHeight;
return;
}
if (mVisibleHeight == visibleHeight) {
return;
}
mVisibleHeight = visibleHeight;
mIsKeyboardShow = mVisibleHeight < mFirstVisibleHeight;
if (mIsKeyboardShow) {
int keyboardHeight = Math.abs(mVisibleHeight - mFirstVisibleHeight);//键盘高度
if (mListener != null) {
mListener.onSoftKeyBoardShow(keyboardHeight);
}
} else {
if (mListener != null) {
mListener.onSoftKeyBoardHide();
}
}
}
public void addOnKeyBoardStateListener(OnKeyBoardStateListener listener) {
this.mListener = listener;
}
public void removeOnKeyBoardStateListener() {
if (mRootLayout != null && mOnGlobalLayoutListener != null) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
mRootLayout.getViewTreeObserver().removeGlobalOnLayoutListener(mOnGlobalLayoutListener);
} else {
mRootLayout.getViewTreeObserver().removeOnGlobalLayoutListener(mOnGlobalLayoutListener);
}
}
if (mListener != null) {
mListener = null;
}
}
public interface OnKeyBoardStateListener {
/**
* @param keyboardHeight 软键盘高度
*/
void onSoftKeyBoardShow(int keyboardHeight);
void onSoftKeyBoardHide();
}
}