RecyclerView聊天布局和自动滑到底部,软键盘顶起布局

先来效果图:

RecyclerView聊天布局和自动滑到底部,软键盘顶起布局_第1张图片RecyclerView聊天布局和自动滑到底部,软键盘顶起布局_第2张图片

activity中初始化view

  public void initView() {
        getWindow().getDecorView().getViewTreeObserver().addOnGlobalLayoutListener(new KeyboardOnGlobalChangeListener());//监听软键盘弹出
        recyclerView = (RecyclerView) findViewById(R.id.chat_listview);
        layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        layoutManager.setStackFromEnd(false);
        recyclerView.setLayoutManager(layoutManager);
        //聊天输入相关view
        inputEdit = (EditText) findViewById(R.id.bar_edit_text);
        btnSend = (Button) findViewById(R.id.bar_btn_send);
    }

软键盘视图监听及自动滑到最底部

 /**
     * 获取一个视图的宽高(软键盘)
     */
    private class KeyboardOnGlobalChangeListener implements ViewTreeObserver.OnGlobalLayoutListener {

        private int getScreenHeight() {
            return ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getHeight();
        }

        @Override
        public void onGlobalLayout() {
            Rect rect = new Rect();
            getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
            int screenHeight = getScreenHeight();
            int keyboardHeight = screenHeight - rect.bottom;//软键盘高度
            if (Math.abs(keyboardHeight) > screenHeight / 5 && !isShow) {
                setScrollBottom();
                isShow = true;
            } else {
                isShow = false;
            }
        }
    }

    private void setScrollBottom() {

        recyclerView.post(() -> {
            recyclerView.scrollToPosition(groupAdapter.getItemCount() - 1);
            View target = layoutManager.findViewByPosition(groupAdapter.getItemCount() - 1);
            if (target != null) {
                // int offset=  recyclerView.getMeasuredHeight() - target.getMeasuredHeight();
                layoutManager.scrollToPositionWithOffset(groupAdapter.getItemCount() - 1, Integer.MAX_VALUE);//滚动偏移到底部
            }
        });
    }

界面布局




    

        
    

    



include_emotion_bar.xml 布局:



    

        

        

            

        

        

        

 

你可能感兴趣的:(RecyclerView聊天布局和自动滑到底部,软键盘顶起布局)