接上篇博客 Dialog嵌Dialog打开软键盘设置布局不向顶部位移方案_Ycocol的博客-CSDN博客
解决思路是监听软键盘的弹出和隐藏
重新写一个软键盘的监听器
public static class SoftKeyBoardListener { private View rootView;//activity的根视 int rootViewVisibleHeight;//纪录根视图的显示高度 private SoftKeyBoardListener.onSoftKeyBoardChangeListener onSoftKeyBoardChangeListener; public SoftKeyBoardListener(Activity activity) { // 获取activity的根视图 rootView = activity.getWindow().getDecorView(); // 监听视图树中全局布局发生改变或者视图树中的某个视图的可视状态发生改变 rootView.getViewTreeObserver().addonGlobalLayoutListener(new ViewTreeObserver.onGlobalLayoutListener() { @Override public void onGlobalLayout() { DisplayMetrics dm = new DisplayMetrics(); activity.getWindowManager().getDefaultDisplay().getRealMetrics(dm); int screenHeight = dm.heightPixels; //获取当前根视图在屏幕上显示的大小 Rect r = new Rect(); rootView.getWindowVisibleDisplayframe(r); int visibleHeight = r.height(); // screenHeight 包括了安全区域在刘海屏上会比 visibleHeight 多一些安全区域正常不会大于 200 if ((screenHeight - visibleHeight) <= 200) { onSoftKeyBoardChangeListener.keyBoardHide(screenHeight, visibleHeight); } else { onSoftKeyBoardChangeListener.keyBoardShow(screenHeight, visibleHeight); } } }); } private void setonSoftKeyBoardChangeListener(SoftKeyBoardListener.onSoftKeyBoardChangeListener onSoftKeyBoardChangeListener) { this.onSoftKeyBoardChangeListener = onSoftKeyBoardChangeListener; } public interface onSoftKeyBoardChangeListener { void keyBoardShow(int screenHeight, int visibleHeight); void keyBoardHide(int screenHeight, int visibleHeight); } public static void setListener(Activity activity, SoftKeyBoardListener.onSoftKeyBoardChangeListener onSoftKeyBoardChangeListener) { SoftKeyBoardListener softKeyBoardListener = new SoftKeyBoardListener(activity); softKeyBoardListener.setonSoftKeyBoardChangeListener(onSoftKeyBoardChangeListener); } }
使用:在keyBoardShow()和keyBoardHide()里分别去对视图的margin做修改,在onCreate()调用,
private void bindingKeyBoardEvent() { try { SoftKeyBoardListener.setListener(mActivity, new SoftKeyBoardListener.onSoftKeyBoardChangeListener() { @Override public void keyBoardShow(int screenHeight, int visibleHeight) { if (mActivity.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { carViewMLP.topMargin = 0; relativeLayout.setLayoutParams(carViewMLP); } else { int h = ((int) (relativeLayout.getHeight() / 6) + ((screenHeight - relativeLayout.getHeight()) / 2)); Log.e("height-->:", "screenHeight = " + screenHeight + "visibleHeight = " + visibleHeight); carViewMLP.topMargin = -((int) (relativeLayout.getHeight() / 6)); relativeLayout.setLayoutParams(carViewMLP); } } @Override public void keyBoardHide(int screenHeight, int visibleHeight) { //键盘隐藏之后恢复默认布局 carViewMLP.topMargin = 0; relativeLayout.setLayoutParams(carViewMLP); } }); } catch (Exception e) { e.printStackTrace(); } }