Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 獲取軟鍵盤高度與顯示控制

編輯:關於 Android 程式設計

在 Android 開發中,軟鍵盤的顯示與隱藏經常需要手動控制。若需要獲取鍵盤高度,則可透過監聽根布局的顯示區域變化來估算。

顯示與隱藏軟鍵盤

可使用 InputMethodManager 呼叫 showSoftInput 或 toggleSoftInput 顯示鍵盤。隱藏時則可呼叫 hideSoftInputFromWindow,並傳入當前窗口令牌。

估算鍵盤高度

myLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    public void onGlobalLayout() {
        Rect r = new Rect();
        myLayout.getWindowVisibleDisplayFrame(r);
        int screenHeight = myLayout.getRootView().getHeight();
        int heightDifference = screenHeight - (r.bottom - r.top);
    }
});

當軟鍵盤彈出時,可見區域高度會減少,兩者差值即可作為鍵盤高度的參考值。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved