监听键盘状态, 在短信的界面我们可以通过该方法监听,输入法是否弹出
conv_root 为根布局的id
// get root layout id
final View activityRootView = findViewById(R.id.conv_root);
// add listener for rootlayou
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// compare Activity layout
int heightDiff = activityRootView.getRootView().getHeight() - activityRootView.getHeight();
int diff = MessageUtils.getScreenHeight()/5;//这里通过5分之1高度来判断键盘是否弹出
InputMethodManager imm = (InputMethodManager)getSystemService( Context.INPUT_METHOD_SERVICE );
if (heightDiff > diff && imm.isActive()) {
// heightDiff bigger then 150, show the softkeyboard
mFloatingActionButtonContainer.setVisibility(View.INVISIBLE);
} else {
// heightDiff little then150, hide the softkeyboard
mFloatingActionButtonContainer.setVisibility(View.VISIBLE);
}
}
});
个人感觉这里最重要的一个方法是
InputMethodManager.<span style="font-family: Arial, Helvetica, sans-serif;">isActive()</span>
这个是系统的原生方法,通过这个值可以最精确的得到键盘状态,但是因为要监听键盘实时状态,所以最好开一个线程,或者是一个监听器
另外如果只是用键盘高度 diff 来判断的话,最好不要将这个值写死。不然会出现屏幕适配性的问题