前言
最近做需求,遇到软键盘弹起底部布局按钮被顶起的情况,需求不一样,对应方法也会存在差异性,说说我遇到的问题及解决过程。
问题
登录页根布局是RelativeLayout,底部有一个登录按钮通过android:layout_alignParentBottom="true"放至最底部,软键盘弹起时按钮会被顶到键盘上,遮住输入框,体验巨差。
修改
1.在manifest里面加入键盘属性android:windowSoftInputMode="adjustPan”,关于它的参数
详情可以看看这篇文章https://www.jianshu.com/p/e59a0b49cdc1。虽然对我没什么用,不过还是记录下,万一对其他人有用呢。
2.布局里面加入Scrollerview,将要显示在软键盘之上的布局包裹起来,这样软键盘会一直在要显示的布局下方,但底部按钮不会跟着上移。亲测在部分机型上有用,但是有个华为手机任然无效。
3.无奈只能监听软键盘的弹起跟收入了,我是这么操作的,上代码
/**
* 监听键盘弹起,防止键盘顶起底部布局
*/
private void setLayoutKayBoard() {
//根布局
RelativeLayout rootView = (RelativeLayout) findViewById(R.id.rl_rootview);
rootView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
/*有的是根据if (bottom - oldBottom < -1) 跟(bottom - oldBottom > 1)来判断软键盘是否弹起的,
但我实际打印出来两个值相等,所以并不能解决我的问题,于是我用了以下方式*/
boolean softInputVisible = KeyboardUtils.isSoftInputVisible(LoginActivity.this);
if (softInputVisible) {
//Todo这个地方可以根据自己具体的业务需求进行相应的操作,我比较粗暴,直接隐藏了
mTvLogin.setVisibility(View.GONE);
} else {
//这里延时是为了交互效果,可以根据自己的情况自行修改
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
mTvLogin.setVisibility(View.VISIBLE);
}
},10);
}
}
});
}
我这里用到了一个软键盘工具类KeyboardUtils:
public final class KeyboardUtils {
private static int sContentViewInvisibleHeightPre;
private static OnGlobalLayoutListener onGlobalLayoutListener;
private static OnSoftInputChangedListener onSoftInputChangedListener;
private KeyboardUtils() {
throw new UnsupportedOperationException("u can't instantiate me...");
}
/**
* Show the soft input.
*
* @param activity The activity.
*/
public static void showSoftInput(final Activity activity) {
InputMethodManager imm =
(InputMethodManager) activity