之前在做的一个即时通讯软件中需要获取键盘的高度,想要做成跟微信和米聊一样的表现形式,但是首先遇到的一个问题就是获取键盘的高度,Google了很久,终于发现了一个比较好用的方法:
// Add these code in activity, such as onCreate method.
final Context context = getApplicationContext();
final RelativeLayout parentLayout = (RelativeLayout) findViewById(R.id.parent);
final View myLayout = getWindow().getDecorView();
parentLayout.getViewTreeObserver(). addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Rect r = new Rect();
// r will be populated with the coordinates of your view that area still visible.
parentLayout.getWindowVisibleDisplayFrame(r);
int screenHeight = myLayout.getRootView().getHeight();
int heightDiff = screenHeight - (r.bottom - r.top);
if (heightDiff > 100)
// if more than 100 pixels, its probably a keyboard
// get status bar height
int statusBarHeight = 0;
try {
Class<?> c = Class.forName("com.android.internal.R$dimen");
Object obj = c.newInstance();
Field field = c.getField("status_bar_height");
int x = Integer.parseInt(field.get(obj).toString());
statusBarHeight = context.getResources().getDimensionPixelSize(x);
} catch (Exception e) {
e.printStackTrace();
}
int realKeyboardHeight = heightDiff - statusBarHeight;
Log.i("keyboard height = " + realKeyboardHeight);
}
}
});
用这种方式获取到的高度基本是正确的,但是在键盘弹出的效果上还是不如微信和米聊,希望后面能够找到更好的方式来优化这一步骤。
看到这篇文章阅读量还是挺多的,可能由于这段代码是我从项目中直接copy出来的,没做多少修改,
myLayout
这个变量不知道是什么布局,给大家带来的困惑请谅解,现在将上面的源码修改了一下,加入了myLayout
的定义。