我有一个RecyclerView,我希望它从顶部拉出时是SwipeRefreshLayout,所以我可以获得最新的20项并在RecyclerView上显示它。同时,当到达底部的第20项时,然后获取另一个来自数据库的第20项。
因此,我得到了下面的最后一项,所以我可以获取下一个第20项。
//for endless scroll
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
visibleItemCount = recyclerView.getChildCount();
totalItemCount = mLayoutManager.getItemCount();
firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition();
if (loading) {
if (totalItemCount > previousTotal) {
loading = false;
previousTotal = totalItemCount;
}
}
if (!loading && (totalItemCount - visibleItemCount)
<= (firstVisibleItem + visibleThreshold)) {
// End has been reached
Log.i("Yaeye!", "end called");
fetchPost(feedItems.get(feedItems.size()-1).getId());
//This function is fetch the next 20th item from database
// Do something
loading = true;
}
}
});
}
当它到达Recycleview的底部时,这是好的,但问题是当现在是顶部(RecyclerView中的第一项)时,我拉下来,假设它获取新项目,但它崩溃。这是错误:
java.lang.ArrayIndexOutOfBoundsException:length = 27;指数= -1
以下是我的代码:,SwipeRefreshLayout
获取数据库中的最新第20项
// show loader and fetch messages
swipeRefreshLayout.post(
new Runnable() {
@Override
public void run() {
clear();
fetchIntialPost(); // this one,fetch the latest item
}
}
);
所以我知道它引起的,当在第1项时,它也考虑到RecyclerView的结束,所以它调用fetchPost(feedItems.get(feedItems.size()-1).getId());
这个函数而不是这个函数fetchIntialPost();
所以现在我的问题是,当在顶部(第1项)时,在向下拉fetchIntialPost();
时调用SwipeRefreshLayout
?和最后一项,只需致电fetchPost(feedItems.get(feedItems.size()-1).getId());
。
由于
答案 0 :(得分:1)
我在执行此行代码feedItems.size()-1
之前检查fetchPost(feedItems.get(feedItems.size()-1).getId());
的值来解决此问题
这是我的工作代码:
//top and bottom also consider end of the list
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
visibleItemCount = recyclerView.getChildCount();
totalItemCount = mLayoutManager.getItemCount();
firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition();
lastVisibleItem = mLayoutManager.findLastVisibleItemPosition();
if (loading) {
if (totalItemCount > previousTotal) {
loading = false;
previousTotal = totalItemCount;
}
}
if (!loading && (totalItemCount - visibleItemCount)
<= (firstVisibleItem + visibleThreshold)) {
// End has been reached
//top and bottom also consider end of the list
Log.i("Yaeye!", "end called");
if(feedItems.size() - 1 > 0) {
//when pull down SwipeRefreshLayout,feedItems.size = -1
//so if greater than 0,means is bottom of the list
// Do something
fetchPost(feedItems.get(feedItems.size() - 1).getId());
loading = true;
}else{
//here is the top of the list
}
}
}
});
答案 1 :(得分:0)
你能试试吗?
lastVisibleItem = mLayoutManager.findLastVisibleItemPosition();
if (!loading && lastVisibleItem == (totalItemCount - 1)) {
// End has been reached
}