Android设置控件一直保持在软键盘上方

没图说个X,先上效果图


再来个布局图


红框部分即我们需要保持在软键盘上方的部分,蓝框部分是父布局

1.声明 LayoutChangeListener

ViewTreeObserver.OnGlobalLayoutListenermLayoutChangeListener =new ViewTreeObserver.OnGlobalLayoutListener() {

    @Override

    public void onGlobalLayout() {

        Rect rect =new Rect();

        final View decorView = getActivity().getWindow().getDecorView();

        decorView.getWindowVisibleDisplayFrame(rect);

        //计算出可见屏幕的高度

        int displayHight = rect.bottom - rect.top;

        //获得屏幕整体的高度

        int hight = decorView.getHeight();

        //获得键盘高度

        int keyboardHeight = hight - displayHight;

        boolean visible = (double) displayHight / hight <0.7;

        //如果屏幕高度和Window可见区域高度差值大于整个屏幕高度的0.7,则表示软键盘显示中,否则软键盘为隐藏状态。

        if (visible) {

            // bottomView 需要跟随软键盘移动的布局,上面提到的红色布局

            // setDuration(0) 默认300, 设置 0 ,表示动画执行时间为0,没有过程,只有动画结果了

            //-keyboardHeight +100这个看手机设置,一般不需要+100

            bottomView.animate().translationY(-keyboardHeight +100).setDuration(0).start();

        }else {

            bottomView.animate().translationY(0).start();

        }

}

};

2.传入初始化后的Edittext

private void showInputManager(EditText editText) { 

 /**

 * OnGlobalLayoutListener 

 * 每次布局变化时都会调用 

 * 界面view 显示消失都会调用,软键盘显示与消失时都调用 

 * */ 

 constraintLayout.getViewTreeObserver().addOnGlobalLayoutListener(mLayoutChangeListener); InputMethodManager inputManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);

}

constraintLayout是上面提到的蓝色部分,也就是父布局

3.注意事项

如果功能没实现,请检查一下项目清单文件AndroidManifest.xml中是否有

android:configChanges="orientation|keyboardHidden|screenSize"等设置,如果有先去掉在看效果。

如还有其他疑问可以评论区留言,楼主看到后会及时回复。

如果本文帮助到了你,还请点个赞支持一下,感谢~

你可能感兴趣的:(Android设置控件一直保持在软键盘上方)