最近做项目的时候要使用emoj表情, emoj标签的输入块要和软键盘的高度一致, 于是有了获取软键盘高度的需求,
废话少说, 下面是我写的一个获取键盘高度的工具类:
public class KeyboardHeightUtils {
/**
* 初始化键盘高度 (键盘弹出时才有效; 首次进入Activity时, 计算的高度newKeyboardHeight=0)
* @param activity
*/
public static void initKeyboardPanelHeight(final Activity activity) {
final int oldKeyboardHeight = getKeyboardHeight();
final View v = activity.findViewById(android.R.id.content);
v.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
Rect r = new Rect();
View rootview = activity.getWindow().getDecorView();
rootview.getWindowVisibleDisplayFrame(r);
int screenHeight = rootview.getRootView().getHeight();
int newKeyboardHeight = screenHeight - r.bottom;
if (newKeyboardHeight > 300) {
if (newKeyboardHeight != oldKeyboardHeight) {
KeyboardHeightUtils.setKeyboardHeight(newKeyboardHeight);
}
v.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
}
});
}
/**
* 获取键盘高度
* @return
*/
public static int getKeyboardHeight() {
return Preferences.getSharedPreferences().getInt(PreferencesKey.PREFS_KEY_KEYBOARD_HEIGHT, 0);
}
/**
* 设置键盘高度
* @param keyboardHeight
*/
public static void setKeyboardHeight(int keyboardHeight) {
Preferences.getSharedPreferences().edit().putInt(PreferencesKey.PREFS_KEY_KEYBOARD_HEIGHT, keyboardHeight).apply();
}
}
可以在有EditText的Activity中调用, 可以在这样的Activity的onCreate中初始化软件盘的高度, 如: KeyboardHeightUtils.initKeyboardPanelHeight(this);
如有错误之处, 欢迎指正 .......