2016-06-11 68 views
1

我在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最终会重新出现,而且我必须导航到另一个片段并从另一个片段中再次运行。

+0

你试过'notifyDataSetChanged'而不是'插入'吗?以防万一 –

+0

@StasLelyuk不,但我解决了这个问题。我不知道我是否找出问题的原因,但无限滚动正在工作。看看我的答案 –

回答

0

这似乎是问题RealmSingleton.addToBottomOfUserFeedRealm(usersFeed)被添加Item s到我的适配器的RealmResults名单异步 - 的Realm一个功能 - 和我后马上打电话FUserFeed.sAdapter.notifyItemRangeInserted()。所以,我通知适配器在插入新项目之前插入了新项目。

所以我所做的是addChangeListener(RealmChangeListener)mItems并在其中调用notifyItemRangeInserted()以确保它只在mItems发生变化后才被调用。

现在它的工作完美;不管我向下滚动多快。

虽然为什么它在我慢慢滚动时起作用,这仍然很奇怪。滚动速度并不影响在该Realm异步添加了项目的mItems,所以notifyItemRangeInserted()应该一直前的项目实际上添加到列表称为速度。然而,如果我足够慢地滚动,实施仍然有效。

相关问题