聊天页面弹出键盘信息滚动到最后一条

本文介绍了一种在聊天应用中实现消息自动滚动到最新位置的方法。通过给RecyclerView的根布局添加addOnLayoutChangeListener监听,监测布局变化,当界面高度减小时自动滚动到最新消息。此外,还介绍了如何通过addOnScrollListener监听区分用户主动滚动的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

效果图:

聊天信息

实现原理:

· 给聊天信息展示RecyclerView的根布局添加addOnLayoutChangeListener()监听

代码实现:

1、xml文件里的信息展示布局如下:(代码仅为页面布局的信息展示部分)

<FrameLayout
        android:id="@+id/fl_chat"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toTopOf="@+id/ll_input"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/rv_chat"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </FrameLayout>

2、在java代码里边的监听设置

//这里flChat为聊天信息展示RecyclerView所在的根布局
        FrameLayout flChat = (FrameLayout) findViewById(R.id.fl_chat);
        flChat.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) {

                    //通过RecyclerView的滚动方法将聊天信息滚动到最后一条
                    rvChat.scrollToPosition(adapterChat.getModels().size() - 1);
                }
            }
        });

3、如果要做到如QQ聊天翻动到中间的时候点击输入框输入内容不滚动最底部,可以给RecyclerView添加addOnScrollListener()监听,判断用户主动滚动查看中间信息部分的话,增加一个boolean值判断,在上部分(2)当中的onLayoutChange()方法判断里增加该boolean值条件。


That’s all, 日常项目当中碰到的小知识点,记录下希望可以帮助到大家。Thank you!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值