我看到了this个问题.这个问题的答案是可行的.但是…我必须创建向两侧滚动.这个答案帮助我达到了最低要求,但是当我到达列表顶部时,我不知道如何发送请求.我试图使用像这样的东西:
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(@NonNull RecyclerView recyclerView,int dx,int dy) {
if(dy > 0) //check for scroll down
{
}
}
});
if(dy == 0)
{
getting some data
}
但这是错误的.为什么?因为在到达列表底部之后加载了一些数据之后,我的列表会自动到达列表顶部并再次加载数据.因此,我必须再添加一个条件,但我无法想象哪个条件.也许有人可以帮我吗?
更新
我试图添加这样的东西:
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(@NonNull RecyclerView recyclerView,int dy) {
if (dy > 0) //check for scroll down
{
pastVisiblesItems = layoutManager.findFirstVisibleItemPosition();
if (loading) {
loading = false;
}
}
if(pastVisiblesItems==5){
loading=true;
}
if (loading&&recyclerView.canScrollVertically(-1)){
if (prev_url != null) {
Log.i("m","[]");
}
}
}
});
但是这种情况:
if (loading&&recyclerView.canScrollVertically(-1)){
if (prev_url != null) {
Log.i("m","[]");
}
}
将发送约30个请求,这对我来说是错误的:(
最佳答案
您可以尝试反转条件以达到滚动侦听器的顶部,如下所示:
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(@NonNull RecyclerView recyclerView,int dy) {
if(dy > 0) //check for scroll down
{
visibleItemCount = mLayoutManager.getChildCount();
totalItemCount = mLayoutManager.getItemCount();
pastVisiblesItems = mLayoutManager.findFirstVisibleItemPosition();
if (loading)
{
if ( (visibleItemCount + pastVisiblesItems) >= totalItemCount)
{
loading = false;
Log.v("...","Last Item Wow !");
//Do pagination.. i.e. fetch new data
}
}
}
if(dy < 0) //check for scroll up
{
visibleItemCount = mLayoutManager.getChildCount();
pastVisiblesItems = mLayoutManager.findLastVisibleItemPosition();
if (loading)
{
if ( (pastVisiblesItems - visibleItemCount) <= 0)
{
loading = false;
Log.v("...","First Item Wow !");
//Do pagination.. i.e. fetch new data
}
}
}
}
});