一,错误方法
1.聊天数据倒序排列,取出前15条做为第一页数据。
2.将数据再次倒序排列,绑定在Adapter中显示。
3.recycleview 滑动到底部
- recycleView.smoothScrollToPosition(adapter.getItemCount());
4.recycleView下拉刷新时,获取第二页数据;同样再次倒序排列,追加到adapter顶部;
- public void appendData(List<BeanChat> chats) {
- if (listChat.size() == 0) {
- listChat = chats;
- } else {
- List<BeanChat> newList = new ArrayList<BeanChat>();
- for (Iterator<BeanChat> it = chats.iterator(); it.hasNext(); ) {
- newList.add(it.next());
- }
- //新数据追加到顶部
- listChat.addAll(0,newList);
- }
- notifyDataSetChanged();
- }
5.用上述方法实现逻辑过于繁琐,而且每次进入聊天界面,会有列表滑动到底部的动画,影响用户体验;
二。方法改进
1.recycleView 设置倒序排列
- LinearLayoutManager layoutManager = (LinearLayoutManager)recycleView.getLayoutManager();
- layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
- layoutManager.setReverseLayout(true);
2.聊天数据倒序排列,取出前15条做为第一页数据。
3.将数据绑定在adapter上
- public void appendData(List<BeanChat> chats) {
- listChat.addAll(chats);
- notifyDataSetChanged();
- }
4.recycleView下拉,滑动到顶部,继续下拉刷新获取第二页数据;
- swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
- @Override
- public void onRefresh() {
- if (15 >= localDataCount) {
- swipeRefreshLayout.setRefreshing(false);
- return;
- }
- getChatList();
- //绑定成功下一页数据后,recycleView向上滑动200像素;(简单实现,优化部分后续处理)
- recycleView.smoothScrollBy(0,-200);
- swipeRefreshLayout.setRefreshing(false);
- }
- });
5.新增发送消息时,将消息追加到消息列表顶端(即展示在recycleView底部)
- public void addData(BeanChat chat) {
- Log.i(TAG,"addData: " + chat.getChatId());
- listChat.add(0,chat);
- notifyItemInserted(0);
- }
6.实现效果预览