12

我有一个 RecyclerView + LinearLayoutManger,它正在使用一个包含聊天消息的适配器。我将聊天消息的数量限制为最近的 100 条。这个问题是当我删除较旧的聊天时,recyclerview 中聊天的滚动位置会发生变化,因为索引 0 已被删除。我开始编写下面的代码:

int firstVisiblePosition = layoutManager.findFirstVisibleItemPosition();
View v = layoutManager.getChildAt(firstVisiblePosition);
if (firstVisiblePosition > 0 && v != null) {
    int offsetTop = //need to get the view offset here;
    chatAdapter.notifyDataSetChanged();

    if (firstVisiblePosition - 1 >= 0 && chatAdapter.getItemCount() > 0) {
        layoutManager.scrollToPositionWithOffset(firstVisiblePosition - 1, offsetTop);
    }
}

我认为很容易获得第一个可见项目位置的可见偏移量。前任。如果第一个可见视图是 300dp 但只有最后一个 200dp 可见,我想获得 100 偏移量。

这样我可以使用 scrollToPositionWithOffset(firstVisiblePosition - 1, offsetTop)。

我在这里错过了什么吗?这似乎是一个容易解决的问题,但我还没有看到任何支持这一点的方法。

4

1 回答 1

14

@黑带。谢谢你让我走上正轨。

我需要的偏移量实际上只是 v.getTop();

我真正的问题出在 getChildAt() 中。显然 getChildAt 从第一个可见位置开始,而不是在适配器的位置。在这种情况下,文档写得不好。

这是生成的代码。

int firstVisiblePosition = layoutManager.findFirstVisibleItemPosition();
View v = layoutManager.getChildAt(0);
if (firstVisiblePosition > 0 && v != null) {
    int offsetTop = v.getTop();
    chatAdapter.notifyDataSetChanged();

    if (firstVisiblePosition - 1 >= 0 && chatAdapter.getItemCount() > 0) {
         layoutManager.scrollToPositionWithOffset(firstVisiblePosition - 1, offsetTop);
    }
}
于 2015-12-01T20:39:13.250 回答