聊天介面中 ListView 顯示消息,輸入框獲取焦點彈出軟鍵盤時,列表底部內容被鍵盤遮擋。需監聽鍵盤彈出事件,動態調整列表滾動或佈局高度。
EditText 焦點變化不可靠:代碼主動彈出鍵盤時,焦點獲取早於鍵盤動畫完成。通過 ViewTreeObserver.OnGlobalLayoutListener 監聽根佈局可見高度變化,推斷鍵盤狀態。
final View rootView = findViewById(android.R.id.content);
rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Rect r = new Rect();
rootView.getWindowVisibleDisplayFrame(r);
int screenHeight = rootView.getRootView().getHeight();
int keypadHeight = screenHeight - r.bottom;
// 經驗值:鍵盤高度超過屏幕 1/3 視為彈出
if (keypadHeight > screenHeight / 3) {
// 鍵盤彈出:滾動 ListView 到最新消息、調整底部 padding 等
} else {
// 鍵盤收起:恢復佈局
}
}
});
KeyboardVisibilityEvent)// build.gradle
implementation 'com.github.yshrsmz:KeyboardVisibilityEvent:2.1.0'
// 使用
KeyboardVisibilityEvent.setEventListener(this, new KeyboardVisibilityEventListener() {
@Override
public void onVisibilityChanged(boolean isOpen) {
// 直接獲得鍵盤開關狀態
}
});
在 AndroidManifest.xml 對應 Activity 中設置:
<activity
android:name=".ChatActivity"
android:windowSoftInputMode="adjustResize|stateAlwaysHidden" />
adjustResize 會自動壓縮佈局高度,配合 ScrollView 或 RecyclerView 通常能解決遮擋問題,無需手動監聽。
adjustResize + RecyclerView(配合 LinearLayoutManager.setStackFromEnd(true))。onDestroy 移除 OnGlobalLayoutListener 防止內存洩漏。