RecycleView设置倒置排序,实现聊天列表界面

前端之家收集整理的这篇文章主要介绍了RecycleView设置倒置排序,实现聊天列表界面前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

一,错误方法
1.聊天数据倒序排列,取出前15条做为第一页数据。
2.将数据再次倒序排列,绑定在Adapter中显示
3.recycleview 滑动到底部

  1. recycleView.smoothScrollToPosition(adapter.getItemCount());

4.recycleView下拉刷新时,获取第二页数据;同样再次倒序排列,追加到adapter顶部;

  1. public void appendData(List<BeanChat> chats) {
  2. if (listChat.size() == 0) {
  3. listChat = chats;
  4. } else {
  5. List<BeanChat> newList = new ArrayList<BeanChat>();
  6. for (Iterator<BeanChat> it = chats.iterator(); it.hasNext(); ) {
  7. newList.add(it.next());
  8. }
  9. //新数据追加到顶部
  10. listChat.addAll(0,newList);
  11. }
  12. notifyDataSetChanged();
  13. }

5.用上述方法实现逻辑过于繁琐,而且每次进入聊天界面,会有列表滑动到底部的动画,影响用户体验;

二。方法改进
1.recycleView 设置倒序排列

  1. LinearLayoutManager layoutManager = (LinearLayoutManager)recycleView.getLayoutManager();
  2. layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
  3. layoutManager.setReverseLayout(true);

2.聊天数据倒序排列,取出前15条做为第一页数据。
3.将数据绑定在adapter上

  1. public void appendData(List<BeanChat> chats) {
  2. listChat.addAll(chats);
  3. notifyDataSetChanged();
  4. }

4.recycleView下拉,滑动到顶部,继续下拉刷新获取第二页数据;

  1. swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
  2. @Override
  3. public void onRefresh() {
  4. if (15 >= localDataCount) {
  5. swipeRefreshLayout.setRefreshing(false);
  6. return;
  7. }
  8. getChatList();
  9. //绑定成功下一页数据后,recycleView向上滑动200像素;(简单实现,优化部分后续处理)
  10. recycleView.smoothScrollBy(0,-200);
  11. swipeRefreshLayout.setRefreshing(false);
  12. }
  13. });

5.新增发送消息时,将消息追加到消息列表顶端(即展示在recycleView底部

  1. public void addData(BeanChat chat) {
  2. Log.i(TAG,"addData: " + chat.getChatId());
  3. listChat.add(0,chat);
  4. notifyItemInserted(0);
  5. }

6.实现效果预览

猜你在找的设计模式相关文章