1、页面只有一个EditText时,只需针对这一个考虑;
/**
* 防止使用了statusbar的沉浸式状态栏,随着键盘上移。
* 当键盘弹起时,让界面整体上移;键盘收起,让界面整体下移。
* https://blog.youkuaiyun.com/xueand/article/details/73293809
* addLayoutListener方法如下
*
* @param rootView 根布局
* @param scrollView 需要显示的最下方View
*/
public static void addLayoutListener(final View rootView, final View scrollView) {
rootView.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
Rect rect = new Rect();
//1、获取main在窗体的可视区域
rootView.getWindowVisibleDisplayFrame(rect);
//2、获取main在窗体的不可视区域高度,在键盘没有弹起时,main.getRootView().getHeight()调节度应该和rect.bottom高度一样
int mainInvisibleHeight = rootView.getRootView().getHeight() - rect.bottom;
int screenHeight = rootView.getRootView().getHeight();//屏幕高度
//3、不可见区域大于屏幕本身高度的1/4:说明键盘弹起了
if (mainInvisibleHeight > screenHeight / 4) {
int[] location = new int[2];
scrollView.getLocationInWindow(location);
// 4、获取Scroll的窗体坐标,算出main需要滚动的高度
int srollHeight = (location[1] + scrollView.getHeight()) - rect.bottom;
//5、让界面整体上移键盘的高度
rootView.scrollTo(0, srollHeight);
} else {
//3、不可见区域小于屏幕高度1/4时,说明键盘隐藏了,把界面下移,移回到原有高度
rootView.scrollTo(0, 0);
}
});
}
2、页面有多个EditText时,防止相互干扰,需要针对特定的EditView进行监听;
/**
* 防止使用了statusbar的沉浸式状态栏,随着键盘上移。
* 当键盘弹起时,让界面整体上移;键盘收起,让界面整体下移。
* https://blog.youkuaiyun.com/xueand/article/details/73293809
* addLayoutListener方法如下
*
* @param scrollView 需要滚动的布局(不包含标题)
* @param editView 需要监听的EditView
*/
public static void addLayoutListener(final View scrollView, final View editView) {
AtomicBoolean focused = new AtomicBoolean(false);
if (editView instanceof EditText) {
editView.setOnFocusChangeListener((v, hasFocus) -> {
focused.set(hasFocus);
LegoLog.d("1、焦点判断");
});
}
scrollView.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
if (!focused.get()) {
LegoLog.d("2、不需要考虑的屏幕变化");
return;
}
LegoLog.d("3、addOnGlobalLayoutListener");
Rect rect = new Rect();
//1、获取main在窗体的可视区域
scrollView.getWindowVisibleDisplayFrame(rect);
//2、获取main在窗体的不可视区域高度,在键盘没有弹起时,main.getRootView().getHeight()调节度应该和rect.bottom高度一样
int mainInvisibleHeight = scrollView.getRootView().getHeight() - rect.bottom;
int screenHeight = scrollView.getRootView().getHeight();//屏幕高度
//3、不可见区域大于屏幕本身高度的1/4:说明键盘弹起了
if (mainInvisibleHeight > screenHeight / 4) {
int[] location = new int[2];
editView.getLocationInWindow(location);
// 4、获取Scroll的窗体坐标,算出main需要滚动的高度
int srollHeight = (location[1] + editView.getHeight()) - rect.bottom;
//5、让界面整体上移键盘的高度
scrollView.scrollTo(0, srollHeight);
} else {
//3、不可见区域小于屏幕高度1/4时,说明键盘隐藏了,把界面下移,移回到原有高度
scrollView.scrollTo(0, 0);
}
});
}
3、如果ScrollView嵌套多个EditView,并且这些EditView都需要监听时:
android沉浸式状态栏下,键盘遮挡输入框问题 (最佳方案)

本文详细介绍了如何在Android应用中,通过监听键盘的弹出与收起,自动调整界面布局,确保EditText始终可见。提供了两种方法,一种适用于单个EditText的情况,另一种适用于多个EditText并需特定监听的情形。
354

被折叠的 条评论
为什么被折叠?



