我在RecyclerView
中通过检查项目在onBindViewHolder()
中的位置以及是否从REST
服务请求了更多项目来实现无限滚动。如果物品的位置距列表末尾小于5,并且当前没有更多物品请求,则执行更多物品的请求。如果RecyclerView
通过慢慢滚动RecyclerView未显示适配器中的所有项目
@Override
public void onBindViewHolder(ItemHolder holder, int position) {
holder.bindHolder(position);
//debugging purposes
//logs the current position, the size of the item list, and whether
//or not more items are already being retrieved from the rest service
Log.d("ADAPTER", "position = " + position +
"\nmItems.size() = " + mItems.size() +
"\nGET_USER_FEED_IS_INACTIVE = " +
HTTPRequests.GET_USER_FEED_IS_INACTIVE + "\n\n");
//query for more items if the user is less than 5 items from the end and
//there is not already an active query
if (position > mPolls.size() - 5 && HTTPRequests.GET_USER_FEED_IS_INACTIVE){
HTTPRequests.GETUsersFeed();
}
}
无限滚动工作正常,但如果我真的快速滚动到年底,查询抓住下一批次的物品,将它们添加到列表中,但RecyclerView
不会移动过去的经常项目,就好像它是列表的结尾。疯狂的部分是,记录清楚地表明列表大于RecyclerView
使其似乎出现,但它不会显示新项目。
以下4日志中创建的最后4,当我滚动到RecyclerView
的底部非常快:
D/ADAPTER: position = 20
mItems.size() = 50
GET_USER_FEED_IS_INACTIVE = true
D/ADAPTER: position = 19
mItems.size() = 50
GET_USER_FEED_IS_INACTIVE = true
D/ADAPTER: position = 23
mItems.size() = 50
GET_USER_FEED_IS_INACTIVE = true
D/ADAPTER: position = 24
mItems.size() = 50
GET_USER_FEED_IS_INACTIVE = true
最后的日志显示onBindViewHolder()
在24位要求的项目 - 的最后一个项目收到第一个查询 - 当时,mItems.size()
是50 - 第二批25项已收到并添加到mItems
。 但是,我不能向下滚动任何更远的项目24.
有关为什么会发生这种情况的任何想法?
。
更新:
这是当我收到从REST
服务的响应运行该代码:
public void onResponse(String response) {
List<Item> usersFeed = sGson.fromJson(response, new TypeToken<ArrayList<Item>>(){}.getType());
//get the size of the adapter's list before new items are added
int initialNumberOfItemsInAdapter = FUserFeed.sAdapter.getItemCount();
//add new items to adapter's list
RealmSingleton.addToBottomOfUserFeedRealm(usersFeed);
//notify adapter of the new items
FUserFeed.sAdapter
.notifyItemRangeInserted(initialNumberOfItemsInAdapter, usersFeed.size());
//signify the end of GETUserFeed activity
GET_USER_FEED_IS_INACTIVE = true;
Log.d("VOLLEY", response);
}
更新: 更奇怪的行为 - 当我浏览到另一个片段,然后回到用户提要片段,RecyclerView
现在认识到列表中有更多项目,所以无限滚动开始再次正常运行。但是如果我再次快速向下滚动,bug最终会重新出现,而且我必须导航到另一个片段并从另一个片段中再次运行。
你试过'notifyDataSetChanged'而不是'插入'吗?以防万一 –
@StasLelyuk不,但我解决了这个问题。我不知道我是否找出问题的原因,但无限滚动正在工作。看看我的答案 –