EditText随着键盘的展示而变化高度

看图中需求,首次进入展示键盘,EditText的高度在键盘之上,看红框位置。当关闭掉键盘,EditText的高度被拉伸,撑满全屏,红框的位置将置屏幕最下端。

首次进入展示出键盘,需要我们在AndroidManifest.xml中配上如下属性:

1
2
3
4
5
6
<activity
android:name=“当前activity”
//不允许横竖屏切换
android:screenOrientation="portrait"
//进入当前activity展示出软键盘
android:windowSoftInputMode="stateAlwaysVisible|adjustResize" />

android:windowSoftInputMode属性在前一篇的EditText键入后的细节优化中有讲解,可参看。

而接下来我们就需要判断键盘什么时候展示和隐藏,并作处理,initSoftKeyboardListener()可在外部调用。代码如下:

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
27
28
29
30
31
private void initSoftKeyboardListener() {
WindowManager wm = (WindowManager) getApplication().getSystemService(Context.WINDOW_SERVICE);
screenHeight = wm.getDefaultDisplay().getHeight();
//键盘弹出控制输入框布局的伸缩
ViewTreeObserver.OnGlobalLayoutListener mLayoutChangeListener = new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
//判断窗口可见区域大小
Rect r = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
//如果屏幕高度和Window可见区域高度差值大于整个屏幕高度的1/3,则表示软键盘显示中,否则软键盘为隐藏状态。
int heightDifference = screenHeight - (r.bottom - r.top);
boolean isKeyboardShowing = heightDifference > screenHeight / 3;
if (isKeyboardShowing) {
//llEditContent是包裹在EditText外部的布局,其子布局分别是EditText和红框中的TextView
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) llEditContent.getLayoutParams();
//软键盘顶部 - title - margin16dp(根据ui设定的值)
params.height = r.bottom - DensityUtils.dp2px(44) - DensityUtils.dp2px(16);
llEditContent.setLayoutParams(params);
} else {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
llEditContent.setLayoutParams(params);
}
}
};
getWindow().getDecorView().getViewTreeObserver().addOnGlobalLayoutListener(mLayoutChangeListener);
}

如需转载,请注明出处:YauLam’s Blog,thank u~