android获得键盘高度,Android获取软键盘高度
在 Android 里我們是無(wú)法直接獲取軟鍵盤(pán)高度的,但是在某些場(chǎng)景下,我們又需要獲取軟鍵盤(pán)的高度。我們可以使用 ViewTreeObserver.OnGlobalLayoutListener來(lái)監(jiān)聽(tīng)窗口大小的變化,當(dāng)軟鍵盤(pán)彈出時(shí),窗口高度會(huì)變小,使用原始窗口高度減去當(dāng)前窗口高度,就可以得出軟鍵盤(pán)的高度了。
//記錄原始窗口高度
private int mWindowHeight = 0;
private ViewTreeObserver.OnGlobalLayoutListener mGlobalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Rect r = new Rect();
//獲取當(dāng)前窗口實(shí)際的可見(jiàn)區(qū)域
getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
int height = r.height();
if (mWindowHeight == 0) {
//一般情況下,這是原始的窗口高度
mWindowHeight = height;
} else {
if (mWindowHeight != height) {
//兩次窗口高度相減,就是軟鍵盤(pán)高度
int softKeyboardHeight = mWindowHeight - height;
System.out.println("SoftKeyboard height = " + softKeyboardHeight);
}
}
}
};
一般我們?cè)?Activity 的 onCreate()方法中開(kāi)始監(jiān)聽(tīng):
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//......
getWindow().getDecorView().getViewTreeObserver().addOnGlobalLayoutListener(mGlobalLayoutListener);
}
請(qǐng)注意當(dāng) Activity 被銷(xiāo)毀的時(shí)候,一定要移除監(jiān)聽(tīng),否則就會(huì)產(chǎn)生內(nèi)存泄漏:
@Override
protected void onDestroy() {
super.onDestroy();
getWindow().getDecorView().getViewTreeObserver().removeOnGlobalLayoutListener(mGlobalLayoutListener);
}
通過(guò)以上方法可以實(shí)時(shí)監(jiān)聽(tīng)軟鍵盤(pán)的高度變化,特別是像有些輸入法例如搜狗,可以隨時(shí)切換拼音輸入、手寫(xiě)輸入,這個(gè)時(shí)候軟鍵盤(pán)的高度都會(huì)發(fā)生變化。
除此之外,還可以通過(guò)該方法判斷軟鍵盤(pán)是否彈出。
總結(jié)
以上是生活随笔為你收集整理的android获得键盘高度,Android获取软键盘高度的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 看看老外是怎么对待免费软件的。
- 下一篇: android sina oauth2.