废话不多说,直接上效果图
然后呢,直接上代码
//在Activity的OnCreate方法里面监听方法
initKeyboardListener();
/**
* 监听软键盘弹出
*/
private void initKeyboardListener() {
View decorView = getWindow().getDecorView();
View contentView = findViewById(Window.ID_ANDROID_CONTENT);
decorView.getViewTreeObserver().addOnGlobalLayoutListener(getGlobalLayoutListener(decorView, contentView));
}
/**
* 软键盘弹出后的处理事件
*/
private ViewTreeObserver.OnGlobalLayoutListener getGlobalLayoutListener(final View decorView, final View contentView) {
return new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Rect rect = new Rect();
decorView.getWindowVisibleDisplayFrame(rect);
int height = decorView.getContext().getResources().getDisplayMetrics().heightPixels;
// 获取键盘抬高的高度
int diff = height - rect.height();
LogWrite.d("height:"+height, LogModel.MODEL_COMMON);
LogWrite.d("rect:"+rect.toString(), LogModel.MODEL_COMMON);
LogWrite.d("diff:"+diff, LogModel.MODEL_COMMON);
if (diff > 0) {
if (contentView.getPaddingBottom() != diff) {
// 将聊天记录定位到最后一行
recyclerView.scrollToPosition(messageAdapter.getItemCount() - 1);
contentView.setPadding(0, 0, 0, diff);
}
} else {
if (contentView.getPaddingBottom() != 0) {
contentView.setPadding(0, 0, 0, 0);
}
}
}
};
}