Android的输入法是否弹出的判断
错误方法
InputMethodManager->isActive
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm.isActive()) {
// the input method has showed
}
Return true if any view is currently active in the input method.
if (getWindow().getAttributes().softInputMode == WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
// the input method has showed
}
经测试结果始终为
SOFT_INPUT_STATE_UNSPECIFIED
不变
可用的方法
- 在需要检测的Activity的layout xml中的root layout指定一个ID
- 代码如下
final View root = findViewById(R.id.root);
root.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int screenHeight = root.getRootView().getHeight();
int myHeight = root.getHeight();
int heightDiff = screenHeight - myHeight;
Log.e("onGlobalLayout", "screenHeight=" + screenHeight);
Log.e("onGlobalLayout", "myHeight=" + myHeight);
if (heightDiff > NORMAL_DIFF) {
Log.e("onGlobalLayout", "Soft keyboard showing");
} else {
Log.e("onGlobalLayout", "Soft keyboard hidden");
}
}
});
- 关于
NORMAL_DIFF
的取值 (此处取100)
screenHeight为整个屏幕的高度(除去虚拟导航栏),myHeight为自身程序所占的高度。
在没有输入法键盘的时候,heightDiff实际就是StatusBar加ActionBar的高度(NORMAL_DIFF),所以只需要根据heightDiff是否大于这个高度就能判断输入法键盘是否显示了。在4.3原生系统上,StatusBar加ActionBar的高度为73dp,建议实际应用将这个值设大一些,因为不同的手机ROM可能这个高度不一致,输入法键盘一般高度在300dp左右
参考资料:
http://m.blog.csdn.net/blog/qujunjie/38085055
http://stackoverflow.com/questions/2150078/how-to-check-visibility-of-software-keyboard-in-android