Android 设置弹出软键盘时布局顶上去的实现方法
介绍
在Android开发中,当软键盘弹出时,为了不遮挡输入框或按钮等控件,我们通常会将布局顶上去。本文将带领你了解整个实现流程,并提供相应的代码和注释。
实现步骤
步骤 | 操作 |
---|---|
1. | 在AndroidManifest.xml文件中为对应的Activity添加android:windowSoftInputMode 属性 |
2. | 在Activity的布局文件中添加ScrollView 作为根布局 |
3. | 设置ScrollView 的android:fillViewport 属性为true |
4. | 将原本的布局放置在ScrollView 中 |
5. | 在Activity中找到根布局,并设置OnGlobalLayoutListener 监听器 |
6. | 在OnGlobalLayoutListener 的回调方法中获取屏幕高度和可见视图的底部坐标 |
7. | 计算键盘高度 = 屏幕高度 - 可见视图底部坐标 |
8. | 根据键盘高度调整布局的底边距 |
代码实现
步骤1:在AndroidManifest.xml文件中添加属性
在需要实现弹出软键盘时布局顶上去的Activity的<activity>
标签中添加以下属性:
<activity
android:name=".YourActivity"
android:windowSoftInputMode="adjustResize|stateHidden" >
adjustResize
属性表示当软键盘弹出时,Activity的布局会重新调整大小以适应软键盘的出现。stateHidden
属性表示当软键盘隐藏时,Activity的状态栏也会隐藏。
步骤2:添加ScrollView作为根布局
在Activity的布局文件中,将原本的根布局替换为ScrollView
:
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<!-- 原本的布局 -->
</ScrollView>
ScrollView
是一个可滚动的容器,当软键盘弹出时,它会根据布局的大小自动滚动。
步骤3:设置ScrollView的fillViewport属性
在ScrollView的属性中添加android:fillViewport="true"
,确保ScrollView充满整个屏幕高度:
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
步骤4:将原本的布局放置在ScrollView中
将原本的布局代码放置在ScrollView标签内,作为ScrollView的子控件:
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<!-- 原本的布局 -->
</ScrollView>
步骤5:设置OnGlobalLayoutListener监听器
在Activity中找到根布局,然后设置OnGlobalLayoutListener
监听器:
View rootView = findViewById(android.R.id.content);
rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// 在此处处理布局改变的逻辑
}
});
通过findViewById(android.R.id.content)
获取到Activity的根布局。
步骤6:获取屏幕高度和可见视图的底部坐标
在OnGlobalLayoutListener
的回调方法中,获取屏幕高度和可见视图的底部坐标:
View rootView = findViewById(android.R.id.content);
rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int screenHeight = rootView.getHeight();
Rect rect = new Rect();
rootView.getWindowVisibleDisplayFrame(rect);
int visibleBottom = rect.bottom;
// 在此处处理布局改变的逻辑
}
});
rootView.getHeight()
可以获取到屏幕的高度,getWindowVisibleDisplayFrame(rect)
可以获取到可见视图的底部坐标。