系统本身没有提供获取虚拟键盘的方法,在网上查了一些资料,发现还存在一点问题,故此把改好的代码记录下来,以备后用。
需要用OnGlobalLayoutListener来监听app窗口的变化
final View decorView = getActivity().getWindow().getDecorView();
//虚拟按键高度
final int vmKeyHeight = getActivity().getResources().getDimensionPixelSize(getResources().getIdentifier("navigation_bar_height", "dimen", "android"));
decorView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Rect rect = new Rect();
decorView.getWindowVisibleDisplayFrame(rect);
int displayHeight = rect.bottom - rect.top;//可见屏幕的高度,不包括顶部状态栏和底部虚拟按键
int keyboardHeight = decorView.getHeight() - displayHeight - rect.top;//这里要减去顶部状态栏高度,否则会不准,看网上的文章大都没减去状态栏高度
if(isVmKeyShow())//如果显示虚拟按键,则还要减去虚拟按键的高度
keyboardHeight-=vmKeyHeight;//这个就是最终虚拟键盘的高度,后面是数据的使用
}
}
});
private boolean isVmKeyShow() {//这个方法在三星手机上测试不好用 Display display = getActivity().getWindowManager().getDefaultDisplay(); Point size=new Point(); Point realSize=new Point(); display.getSize(size); display.getRealSize(realSize); return size.y!=realSize.y; }
上面判断虚拟按键的方式在三星手机上测试不好用,故此改了整体代码,目的是切换输入法及虚拟按键,保持输入框位置不变,如下
final View decorView = getActivity().getWindow().getDecorView(); //获取虚拟按键高度 int id = getResources().getIdentifier("navigation_bar_height", "dimen", "android"); final int vmKeyHeight =id==0? 0: getActivity().getResources().getDimensionPixelSize(id); decorView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { Rect rect = new Rect(); decorView.getWindowVisibleDisplayFrame(rect); int displayHeight = rect.bottom - rect.top;//可见屏幕的高度,不包括顶部状态栏和底部虚拟按键 int keyboardHeight = decorView.getHeight() - displayHeight - rect.top;//包括虚拟按键 int bottomHeight = EdoPreference.getInt(EdoPreference.KEY_KEYBOARD_HEIGHT, 0); if(rect.bottom<decorView.getHeight()){//虚拟按键显示 if(keyboardHeight>vmKeyHeight){//键盘处于显示状态 keyboardHeight-=vmKeyHeight; if(keyboardHeight==bottomHeight){ isKeyboardLastShow=true; return; } bottomHeight=keyboardHeight; }else {//只有虚拟按键显示,isKeyboardLastShow是boolean全局变量 if(!isKeyboardLastShow) bottomHeight-=vmKeyHeight; } isKeyboardLastShow=true; }else{ if(isKeyboardLastShow) bottomHeight+=vmKeyHeight; isKeyboardLastShow=false; } if (1.0 * bottomHeight / displayHeight > 0.4) { chatBottomView.setContentViewHeight(bottomHeight); EdoPreference.setPref(EdoPreference.KEY_KEYBOARD_HEIGHT, bottomHeight); } } });