第一步:
private int mWindowHeight = 0;
private ViewTreeObserver.OnGlobalLayoutListener mGlobalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
private int softKeyboardHeight;
@Override
public void onGlobalLayout() {
Rect r = new Rect();
//获取当前窗口实际的可见区域
getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
int height = r.height();
int width = r.width();
if (mWindowHeight == 0) {
//一般情况下,这是原始的窗口高度
mWindowHeight = height;
setViewLayoutParams(evEmoji, width, 835);
} else {
if (mWindowHeight != height) {
//两次窗口高度相减,就是软键盘高度 835
softKeyboardHeight = mWindowHeight - height;
setViewLayoutParams(evEmoji, width, softKeyboardHeight);
}
}
}
};
第二步:
/**
* 重设 view 的宽高
*
* @param view 将View设置为和软键盘一样的高度
* @param nWidth
* @param nHeight
*/
public static void setViewLayoutParams(View view, int nWidth, int nHeight) {
ViewGroup.LayoutParams lp = view.getLayoutParams();
if (lp.height != nHeight || lp.width != nWidth) {
lp.width = nWidth;
lp.height = nHeight;
view.setLayoutParams(lp);
}
}
第三步:
在onCreate方法中调用
getWindow().getDecorView().getViewTreeObserver().addOnGlobalLayoutListener(mGlobalLayoutListener);
1、比如把输入框封装在dialog中,此时需要手动控制键盘的显示与隐藏的方法:
/**
* 因为这个软键盘是在Dialog中打开的,所以也只能在Dialog中关掉
*/
private void hideKeyBoard() {
((InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE)).
hideSoftInputFromWindow(etCommentContent.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
/**
* 因为这个软键盘是在Dialog中打开的,所以也只能在Dialog中关掉
*/
private void showKeyBoard() {
InputMethodManager inputMethodManager = (InputMethodManager) etCommentContent.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.showSoftInput(etCommentContent, 0);
}