效果图:
实现原理:
· 给聊天信息展示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!