懒惰在android中加载recyclerView

问题描述 投票:6回答:2

有没有人知道如何在Android中实现Lazy Loading recyclelerView?我对android很新,我不知道如何解决这个问题。如果有人帮忙,我会感激不尽。

android android-recyclerview lazy-loading
2个回答
6
投票

您可以使用EndlessRecyclerView

概述常见的应用程序功能是在用户滚动项目(即无限滚动)时自动加载更多项目。这是通过在用户超过剩余项目的阈值之前触发对更多数据的请求来完成的。

这里记录了ListView,GridView和RecyclerView(ListView的后继者)的方法。两者在代码中类似,只是需要传递RecyclerView中的LayoutManager以提供实现无限滚动所需的信息。

在这两种情况下,实现滚动所需的信息包括确定列表中的最后一个可见项以及某种类型的阈值,以便在到达最后一个项之前开始获取更多数据。此数据可用于决定何时从外部源加载更多数据:To provide the appearance of endless scrolling, it's important to fetch data before the user gets to the end of the list. Adding a threshold value therefore helps anticipate the need to append more data.

使用ListView或GridView实现 每个AdapterView(例如ListView和GridView)都支持绑定OnScrollListener事件,只要用户滚动集合就会触发这些事件。使用这个系统,我们可以通过创建扩展OnScrollListener的自己的类来定义一个基本的EndlessScrollListener,它支持大多数用例:

import android.widget.AbsListView; 

public abstract class EndlessScrollListener implements AbsListView.OnScrollListener {
    // The minimum number of items to have below your current scroll position
    // before loading more.
    private int visibleThreshold = 5;
    // The current offset index of data you have loaded
    private int currentPage = 0;
    // The total number of items in the dataset after the last load
    private int previousTotalItemCount = 0;
    // True if we are still waiting for the last set of data to load.
    private boolean loading = true;
    // Sets the starting page index
    private int startingPageIndex = 0;

    public EndlessScrollListener() {
    }

    public EndlessScrollListener(int visibleThreshold) {
        this.visibleThreshold = visibleThreshold;
    }

    public EndlessScrollListener(int visibleThreshold, int startPage) {
        this.visibleThreshold = visibleThreshold;
        this.startingPageIndex = startPage;
        this.currentPage = startPage;
    }


    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) 
        {
        // If the total item count is zero and the previous isn't, assume the
        // list is invalidated and should be reset back to initial state
        if (totalItemCount < previousTotalItemCount) {
            this.currentPage = this.startingPageIndex;
            this.previousTotalItemCount = totalItemCount;
            if (totalItemCount == 0) { this.loading = true; } 
        }
        // If it's still loading, we check to see if the dataset count has
        // changed, if so we conclude it has finished loading and update the current page
        // number and total item count.
        if (loading && (totalItemCount > previousTotalItemCount)) {
            loading = false;
            previousTotalItemCount = totalItemCount;
            currentPage++;
        }

        // If it isn't currently loading, we check to see if we have breached
        // the visibleThreshold and need to reload more data.
        // If we do need to reload some more data, we execute onLoadMore to fetch the data.
        if (!loading && (firstVisibleItem + visibleItemCount + visibleThreshold) >= totalItemCount ) {
            loading = onLoadMore(currentPage + 1, totalItemCount);
        }
    }

    // Defines the process for actually loading more data based on page
    // Returns true if more data is being loaded; returns false if there is no more data to load.
    public abstract boolean onLoadMore(int page, int totalItemsCount);

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        // Don't take any action on changed
    }
}

请注意,这是一个抽象类,为了使用它,您必须扩展此基类并定义onLoadMore方法以实际检索新数据。我们现在可以在任何扩展EndlessScrollListener并将其绑定到AdapterView的活动中定义一个匿名类。例如:

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // ... the usual 
        ListView lvItems = (ListView) findViewById(R.id.lvItems);
        // Attach the listener to the AdapterView onCreate
        lvItems.setOnScrollListener(new EndlessScrollListener() {
          @Override
          public boolean onLoadMore(int page, int totalItemsCount) {
              // Triggered only when new data needs to be appended to the list
              // Add whatever code is needed to append new items to your AdapterView
              loadNextDataFromApi(page); 
              // or loadNextDataFromApi(totalItemsCount); 
              return true; // ONLY if more data is actually being loaded; false otherwise.
          }
        });
    }


   // Append the next page of data into the adapter
   // This method probably sends out a network request and appends new data items to your adapter. 
   public void loadNextDataFromApi(int offset) {
      // Send an API request to retrieve appropriate paginated data 
      //  --> Send the request including an offset value (i.e `page`) as a query parameter.
      //  --> Deserialize and construct new model objects from the API response
      //  --> Append the new data objects to the existing set of items inside the array of items
      //  --> Notify the adapter of the new items made with `notifyDataSetChanged()`
   }
}

现在滚动时,项目将自动填充,因为一旦用户越过visibleThreshold,就会触发onLoadMore方法。这种方法对于GridView同样有效,并且侦听器提供对页面和totalItemsCount的访问,以支持基于分页和基于偏移的提取。

使用RecyclerView实现我们可以通过定义一个需要实现onLoadMore()方法的EndlessRecyclerViewScrollListener接口,与RecyclerView使用类似的方法。 LayoutManager负责在RecyclerView中呈现项目应放置的位置并管理滚动,它提供有关当前相对于适配器的滚动位置的信息。出于这个原因,我们需要传递一个使用LayoutManager的实例来收集必要的信息,以确定何时加载更多数据。为RecyclerView实现无限分页需要执行以下步骤: 为RecyclerView实现无限分页需要执行以下步骤: 1.将EndlessRecyclerViewScrollListener.java复制到您的应用程序中。 2.在RecyclerView上调用addOnScrollListener(...)以启用无限分页。传入EndlessRecyclerViewScrollListener的实例并实现onLoadMore,只要需要加载新页面以填充列表,就会触发该onLoadMore。 3.在上述onLoadMore方法中,通过发送网络请求或从其他源加载,将其他项加载到适配器中。

要开始处理步骤2和3的滚动事件,我们需要在Activity或Fragment中使用addOnScrollListener()方法,并使用布局管理器传递EndlessRecyclerViewScrollListener的实例,如下所示:

public class MainActivity extends Activity {
    // Store a member variable for the listener
    private EndlessRecyclerViewScrollListener scrollListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
       // Configure the RecyclerView
       RecyclerView rvItems = (RecyclerView) findViewById(R.id.rvContacts);
       LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
       rvItems.setLayoutManager(linearLayoutManager);
       // Retain an instance so that you can call `resetState()` for fresh searches
       scrollListener = new EndlessRecyclerViewScrollListener(linearLayoutManager) {
           @Override
           public void onLoadMore(int page, int totalItemsCount, RecyclerView view) {
               // Triggered only when new data needs to be appended to the list
               // Add whatever code is needed to append new items to the bottom of the list
               loadNextDataFromApi(page);
           }
      };
      // Adds the scroll listener to RecyclerView
      rvItems.addOnScrollListener(scrollListener);
  }

  // Append the next page of data into the adapter
  // This method probably sends out a network request and appends new data items to your adapter. 
  public void loadNextDataFromApi(int offset) {
      // Send an API request to retrieve appropriate paginated data 
      //  --> Send the request including an offset value (i.e `page`) as a query parameter.
      //  --> Deserialize and construct new model objects from the API response
      //  --> Append the new data objects to the existing set of items inside the array of items
      //  --> Notify the adapter of the new items made with `notifyItemRangeInserted()`
  }
}

https://github.com/codepath/android_guides/wiki/Endless-Scrolling-with-AdapterViews-and-RecyclerView


-1
投票

我认为这更好,因为你不需要特定版本的minsdk

第1步:创建界面

interface caller{
void call();
}

第2步:在RecycleView上创建调用者

第3步:检查是最后一项?怎么样 ?

在你onBindViewHolder上的Recyclerview

if (position==items.size()-1){// its a last item
           callbacker.call();
}

第4步:在您的活动上创建您的回收站视图定义和 传递给您的recycler视图构造函数

callbacker call{
recyclerParamerList.addAll(ItemList items());
youradapter.notifyDataSetChanged();
}
© www.soinside.com 2019 - 2024. All rights reserved.