android 聊天界面 软键盘弹出顶起界面解决

参考:https://blog.csdn.net/I_do_can/article/details/71159198?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.nonecase

首先上布局
android 聊天界面 软键盘弹出顶起界面解决_第1张图片




    

        

        

    
    

        

        

        
    

java代码

View move_root;
View rl_input;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // full screen

//全屏
this.getWindow().setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);

    move_root= findViewById(R.id.move_root);
    rl_input= findViewById(R.id.rl_input);

    addSoftKeyBoardListener(move_root,rl_input);

}

private ViewTreeObserver.OnGlobalLayoutListener mSoftKeyBoardListener;

private class SoftKeyBoardListener implements ViewTreeObserver.OnGlobalLayoutListener {

    private View root;
    private View view;

    int lastHeight = 0;
    int lastBottom = -1;

    SoftKeyBoardListener(View r,View v) {
        root = r;
        view = v;
    }

    @Override
    public void onGlobalLayout() {
        Rect rect = new Rect();
        root.getWindowVisibleDisplayFrame(rect);
        if (lastBottom == -1) {
            lastBottom = rect.bottom;
            return;
        }

        int nb = rect.bottom;
        int ob = lastBottom;

        if (nb < ob) {
            // 键盘显示了, 滑上去
            int[] location = new int[2];
            view.getLocationInWindow(location);
            int scrollHeight = (location[1] + view.getHeight()) - nb;
            root.scrollTo(0, scrollHeight);
            lastHeight = scrollHeight;
        }
        else if (nb > ob) {
            // 键盘隐藏了, 滑下来
            root.scrollTo(0, 0);
        }

        if (nb != ob) {
            lastBottom = nb;
        }
    }
}

public void removeSoftKeyBoardListener(@NonNull View root) {
    if(mSoftKeyBoardListener != null){
        root.getViewTreeObserver().removeOnGlobalLayoutListener(mSoftKeyBoardListener);
    }
}

public void addSoftKeyBoardListener(final View root, final View view) {
    mSoftKeyBoardListener = new SoftKeyBoardListener(root,view);
    root.getViewTreeObserver().addOnGlobalLayoutListener(mSoftKeyBoardListener);
}

@Override
protected void onDestroy() {
    super.onDestroy();
    removeSoftKeyBoardListener(move_root);
}

你可能感兴趣的:(android 聊天界面 软键盘弹出顶起界面解决)