1. 程式人生 > >如何監聽軟鍵盤的顯示與隱藏

如何監聽軟鍵盤的顯示與隱藏

parentLayout.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {


@Override
public void onGlobalLayout() {
Rect r = new Rect();
parentLayout.getWindowVisibleDisplayFrame(r);
int screenHeight = parentLayout.getRootView()
.getHeight();
int heightDifference = screenHeight - (r.bottom);
if (heightDifference > 200) {
isKeyBoardVisible = true;
// changeKeyboardHeight(heightDifference);
} else {
isKeyBoardVisible = false;
}
}

});

//parentLayout為佈局父控制元件,因為當軟體盤顯示和隱藏時當windowSoftInputMode為adjustResize時parentLayout會調

//用onsizechange方法,因此對佈局樹進行監聽可以判讀出軟體盤的顯示與隱藏