接到产品同学的需求,当用户点击控件时,自动调整布局使其上移,避免被软键盘遮挡. 按如下方法实现了:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
final View rootView = findViewById(android.R.id.content);
rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
private int mPreviousKeyboardHeight = -1;

@Override
public void onGlobalLayout() {
Rect r = new Rect();
rootView.getWindowVisibleDisplayFrame(r);
int screenHeight = rootView.getRootView().getHeight();
int keypadHeight = screenHeight - r.bottom;

if (keypadHeight != mPreviousKeyboardHeight) {
// 键盘高度发生变化,进行相应的布局调整
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) rootView.getLayoutParams();
if (keypadHeight > screenHeight * 0.15) { // 0.15是一个阈值,用于判断是否是键盘所致
// 键盘弹出,调整布局位置
params.bottomMargin = keypadHeight;
} else {
// 键盘关闭或者变化不大,恢复原状
params.bottomMargin = 0;
}
rootView.setLayoutParams(params);
mPreviousKeyboardHeight = keypadHeight;
}
}
});