我在SwipeRefreshLayout中有一个RecyclerView,因此在刷新RecyclerView时会重置。但是,一旦我到达RecyclerView的底部或过度滚动它,我想添加更多项目。
到目前为止我的尝试:
我已经将RecyclerView子类化,一旦达到底部就会实现添加元素(在OnScrollListener中):
LinearLayoutManager manager = (LinearLayoutManager) getLayoutManager();
mVisible = manager.getChildCount();
mTotal = manager.getItemCount();
mPastVisible = manager.findFirstVisibleItemPosition();
if (!loading)
{
if (manager.findLastCompletelyVisibleItemPosition() ==
manager.getItemCount() - 1)
{
loading = true;
loadNext();
}
}
loadNext()
是一个异步请求,它在完成时将loading
布尔值设置为false,并设置适配器,如下所示:
MyAdapter adapter = new MyAdapter(items, ctx);
setAdapter(adapter);
scrollToPosition(mTotal - 1);
loading = false;
项目已正确加载,但scrollToPosition(mTotal - 1);
使最后一项成为第一项,而新项目则添加到底部,因为进入的视图是动画的,旧视图有时会保持绘制状态在后台/前景中,而新的滑过它们。有没有办法以更好的方式实现这一点?
答案 0 :(得分:1)
你可以试试这个:
private RecyclerView.OnScrollListener scrollListener = new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int visibleCount = manager.getChildCount();
int totalCount = manager.getItemCount();
int firstVisibleCount = manager.findFirstVisibleItemPosition();
if (loading && totalCount > previousTotalCount){
loading = false;
previousTotalCount = totalCount;
}
if (!loading && totalCount - visibleCount <= firstVisibleCount + 5){
loading = true;
loadNext();
}
}
};
,您无需致电scrollToPosition()