Android监听软键盘状态

时间:2022-05-09 00:30:55

监听软键盘隐藏或显示,代码如下:

/**
* 监听软键盘状态
*/
private void listenerInput() {
final LinearLayout ll_main = (LinearLayout) findViewById(R.id.activity_main);

ll_main.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Rect rect = new Rect();
ll_main.getWindowVisibleDisplayFrame(rect);
int rootInvisibleHeight = ll_main.getRootView().getHeight() - rect.bottom;
Log.d(TAG, "lin.getRootView().getHeight()=" + ll_main.getRootView().getHeight() +
",rect.bottom=" + rect.bottom + ",rootInvisibleHeight=" + rootInvisibleHeight);
if (rootInvisibleHeight <= 100) {
//软键盘隐藏啦
Toast.makeText(MainActivity.this, "软键盘隐藏啦。。。。。。。",
Toast.LENGTH_SHORT).show();
} else {
//软键盘弹出啦
Toast.makeText(MainActivity.this, "软键盘弹出啦。。。。。。。",
Toast.LENGTH_SHORT).show();
}

}
});

}