实施无尽的RecyclerView

Ale*_*mbo 2 android endlessscroll android-recyclerview

我想实现一个无休止的RecyclerView,但到目前为止,我所遇到的所有实现和教程都描述了从服务器加载数据,然后加载数据或使用循环动态添加元素。

就我而言,我已经有一个大的ArrayList,其中包含要在RecyclerView中显示的数据。

我需要说的是,显示数组的前10个项目,加载更多后,显示下一批10。

Mur*_*göz 6

这可以实现您的目标。

public abstract class EndlessRecyclerOnScrollListener extends RecyclerView.OnScrollListener {
    public static String TAG = EndlessRecyclerOnScrollListener.class.getSimpleName();

private int previousTotal = 0; // The total number of items in the dataset after the last load
private boolean loading = true; // True if we are still waiting for the last set of data to load.
private int visibleThreshold = 5; // The minimum amount of items to have below your current scroll position before loading more.
int firstVisibleItem, visibleItemCount, totalItemCount;

private int current_page = 1;

private LinearLayoutManager mLinearLayoutManager;

public EndlessRecyclerOnScrollListener(LinearLayoutManager linearLayoutManager) {
    this.mLinearLayoutManager = linearLayoutManager;
}

@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
    super.onScrolled(recyclerView, dx, dy);

    visibleItemCount = recyclerView.getChildCount();
    totalItemCount = mLinearLayoutManager.getItemCount();
    firstVisibleItem = mLinearLayoutManager.findFirstVisibleItemPosition();

    if (loading) {
        if (totalItemCount > previousTotal) {
            loading = false;
            previousTotal = totalItemCount;
        }
    }
    if (!loading && (totalItemCount - visibleItemCount)
            <= (firstVisibleItem + visibleThreshold)) {
        // End has been reached

        // Do something
        current_page++;

        onLoadMore(current_page);

        loading = true;
    }
}

public abstract void onLoadMore(int current_page);
}
Run Code Online (Sandbox Code Playgroud)

和样本活动

public class SampleActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sample);

    RecyclerView recyclerView = (RecyclerView) findViewById(R.id.list);
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(linearLayoutManager);
    recyclerView.setOnScrollListener(new EndlessRecyclerOnScrollListener(linearLayoutManager) {
        @Override
        public void onLoadMore(int current_page) {
            // do something...
        }
    });
}
}
Run Code Online (Sandbox Code Playgroud)

编辑:参见此处:使用AdapterViews进行无尽滚动