记录最近项目中遇到的问题:
1、
页面布局:类似于登录注册,包含多个 EditText。为了适配屏幕小的手机,最外层套了一个 NestScrollView 用于滑动
问题描述:软键盘弹出时会将整个布局往上顶,并且距离输入法会有一大段的空白导致界面很难看
想要的效果:软键盘将界面顶起,但是最后一个输入项贴近输入法
解决思路:adjustPan 属性适用于底部有按钮,输入法将按钮顶起的情况。adjustPan 会将整个 activity 向上滚动,如果底部有按钮,会将其依旧停靠在底部,将其遮挡,保持界面的美观。但是 adjustPan 并没有解决我的 EditText 距离输入法有一大段空白的问题,各种调整边距都不行(到现在也不知道是什么原因,请大神指教)。于是试了一下 adjustResize 属性,这个属性会将 activity 整体向上压缩,使得 EditText 贴近输入法,至此解决问题,但是不明白原理。
2、关于输入法弹出/收起的监听。
需求:同样是底部有按钮的情况,但这次的布局是在 Fragment 中,在父 Activity 中添加 adjustPan 属性也不起作用,于是监听输入法的弹出/收起,手动隐藏底部按钮。
这里采用了这篇博客(https://blog.csdn.net/ShuSheng0007/article/details/81511764)所讲述的方法,有一些博客通过监听布局 layout 的改变来判断软键盘的弹出,但是必须是 layout 有变化才会有效果,不适用我的情况。
下面的代码转自这篇博客:
监听类:
public class KeyboardStateObserver {
private static final String TAG = KeyboardStateObserver.class.getSimpleName();
public static KeyboardStateObserver getKeyboardStateObserver(Activity activity) {
return new KeyboardStateObserver(activity);
}
private View mChildOfContent;
private int usableHeightPrevious;
private OnKeyboardVisibilityListener listener;
public void setKeyboardVisibilityListener(OnKeyboardVisibilityListener listener) {
this.listener = listener;
}
private KeyboardStateObserver(Activity activity) {
FrameLayout content = (FrameLayout) activity.findViewById(android.R.id.content);
mChildOfContent = content.getChildAt(0);
mChildOfContent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
possiblyResizeChildOfContent();
}
});
}
private void possiblyResizeChildOfContent() {
int usableHeightNow = computeUsableHeight();
if (usableHeightNow != usableHeightPrevious) {
int usableHeightSansKeyboard = mChildOfContent.getRootView().getHeight();
int heightDifference = usableHeightSansKeyboard - usableHeightNow;
if (heightDifference > (usableHeightSansKeyboard / 4)) {
if (listener != null) {
listener.onKeyboardShow();
}
} else {
if (listener != null) {
listener.onKeyboardHide();
}
}
usableHeightPrevious = usableHeightNow;
Log.d(TAG,"usableHeightNow: " + usableHeightNow + " | usableHeightSansKeyboard:" + usableHeightSansKeyboard + " | heightDifference:" + heightDifference);
}
}
private int computeUsableHeight() {
Rect r = new Rect();
mChildOfContent.getWindowVisibleDisplayFrame(r);
Log.d(TAG,"rec bottom>" + r.bottom + " | rec top>" + r.top);
return (r.bottom - r.top);// 全屏模式下: return r.bottom
}
public interface OnKeyboardVisibilityListener {
void onKeyboardShow();
void onKeyboardHide();
}
}
使用:
//监听软键盘弹出/收回
mKeyboardStateObserver.getKeyboardStateObserver(this).
setKeyboardVisibilityListener(new KeyboardStateObserver.OnKeyboardVisibilityListener() {
@Override
public void onKeyboardShow() {
//软键盘弹出之后的处理
}
@Override
public void onKeyboardHide() {
//软键盘收起之后的处理
}
});