我在使用回收站视图在android中实现无限滚动时遇到问题。我想要的是,基本上,像instagram一样,你无休止地滚动页面。
我有一个包含10个项目的Firebase数据库,我想要显示3个项目并为接下来的两个项目充电,然后当您滚动下两个项目时开始加载下一个项目,依此类推。 (您将看到示例中的大部分内容都是硬编码的。)
我无法像这样制作Firebase查询:
myRef.orderByChild("id").startAt(page*5 + "").endAt(5+page*5 + "")
我想要获得的是在我当前位置接下来的5个项目和id之间 - 让我们说 - 5和10.但是,当我这样做时:
myRef.orderByChild("id").startAt(page*5 + "").endAt(5+page*5 + "")
.getRef().addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
int i = 0;
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
if(i == 5) break;
mDataset.add(postSnapshot.getValue(Card.class));
i++;
}
mAdapter = new CustomAdapter(mDataset);
mRecyclerView.setAdapter(mAdapter);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
所有postSnapshots都会返回ID 1,2,3,4,5。这样可以无休止地滚动,但每次都会收取相同的5个项目。
由于
编辑:
EndlessScrollListener
public abstract class EndlessScrollListener extends RecyclerView.OnScrollListener {
private int mVisibleThreshold = 2,
mCurrentPage = 0,
mPreviousTotalItemCount = 0,
mStartingPageIndex = 0;
private boolean mLoading = true;
RecyclerView.LayoutManager mLayoutManager;
public EndlessScrollListener(){}
public EndlessScrollListener(LinearLayoutManager layoutManager){
mLayoutManager = layoutManager;
}
public EndlessScrollListener(int visibleThreshold){
mVisibleThreshold = visibleThreshold;
}
public int getLastVisibleItem(int[] lastVisibleItemPositions){
int maxSize = lastVisibleItemPositions[0];
for(int i = 1; i < lastVisibleItemPositions.length; ++i){
if(lastVisibleItemPositions[i] > maxSize)
maxSize = lastVisibleItemPositions[i];
}
return maxSize;
}
@Override
public void onScrolled(RecyclerView view, int dx, int dy){
int lastVisibleItemPosition = 0,
totalItemCount = mLayoutManager.getItemCount();
if (mLayoutManager instanceof LinearLayoutManager) {
lastVisibleItemPosition =
((LinearLayoutManager) mLayoutManager).findLastVisibleItemPosition();
}
if(totalItemCount < mPreviousTotalItemCount){
mCurrentPage = mStartingPageIndex;
mPreviousTotalItemCount = totalItemCount;
mLoading = totalItemCount == 0;
}
if(mLoading && totalItemCount > mPreviousTotalItemCount){
mLoading = false;
mPreviousTotalItemCount = totalItemCount;
}
if(!mLoading && (lastVisibleItemPosition + mVisibleThreshold) > totalItemCount){
mCurrentPage++;
onLoadMore(mCurrentPage, totalItemCount, view);
mLoading = true;
}
}
public abstract void onLoadMore(int page, int totalItemsCount, RecyclerView view);
public void resetState(){
mCurrentPage = mStartingPageIndex;
mPreviousTotalItemCount = 0;
mLoading = true;
}
}
在其活动中
scrollListener = new EndlessScrollListener(mLayoutManager) {
@Override
public void onLoadMore(int page, int totalItemsCount, RecyclerView view) {
System.out.println("Dale... Page: " + page + " items: " + totalItemsCount);
loadData(page);
}
};