1. 程式人生 > >Android 輸入鍵盤彈出隱藏監聽

Android 輸入鍵盤彈出隱藏監聽

父佈局 註冊監聽
parent.getViewTreeObserver().addOnGlobalLayoutListener(this);//parent指父佈局控制元件變數

重寫監聽方法
@Override
public void onGlobalLayout() {
//判斷視窗可見區域大小
Rect r = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame®; //如果螢幕高度和Window可見區域高度差值大於整個螢幕高度的1/3,則表示軟鍵盤顯示中,否則軟鍵盤為隱藏狀態。
int screenHeight = DensityUtil.getPhoneHeight(this);
int heightDifference = screenHeight - (r.bottom - r.top);
boolean isKeyboardShowing = heightDifference > screenHeight / 3; //如果之前軟鍵盤狀態為顯示,現在為關閉,或者之前為關閉,現在為顯示,則表示軟鍵盤的狀態發生了改變
if ((mIsSoftKeyboardShowing && !isKeyboardShowing) || (!mIsSoftKeyboardShowing &&isKeyboardShowing)) {
mIsSoftKeyboardShowing = isKeyboardShowing;
if (mIsSoftKeyboardShowing) {
//在這裡 輸入法顯示
} else {
//在這裡 輸入法隱藏
}
}
}

呼叫軟鍵盤顯示
private void showInputMethod() {
//自動彈出軟鍵盤
InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
}