Android监听键盘打开或关闭

时间:2021-01-04 22:39:08
1.AndroidManifes 当前Activity下添加属性
 android:windowSoftInputMode="stateAlwaysHidden|adjustResize"

2.Oncreate调用

 private void listenKeyboard() {
// TODO Auto-generated method stub
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
detailMainRL = (LinearLayout) findViewById(R.id.root_layout);
detailMainRL.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener(){
@Override
public void onGlobalLayout()
{
int heightDiff = detailMainRL.getRootView().getHeight() - detailMainRL.getHeight();
if (heightDiff > detailMainRL.getRootView().getHeight()/3)
{ // 说明键盘是弹出状态
Toast.makeText(MainActivity.this, "open", Toast.LENGTH_SHORT).show();
} else{
Toast.makeText(MainActivity.this, "close", Toast.LENGTH_SHORT).show();
}
}
});
}
  注:detaiMainRL为根布局id

疑问:当布局中设置状态栏,导航栏时,获取键盘高度失效,有知道的大神,请解答下