lts*_*sai 32 android android-recyclerview
我试图让我的RecyclerView循环回到我的列表的开头.
我已经搜遍了整个互联网,并设法检测到我的列表何时到达,但是我不确定从哪里开始.
这是我目前用于检测列表末尾的内容(在此处找到):
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
visibleItemCount = mLayoutManager.getChildCount();
totalItemCount = mLayoutManager.getItemCount();
pastVisiblesItems = mLayoutManager.findFirstVisibleItemPosition();
if (loading) {
if ( (visibleItemCount+pastVisiblesItems) >= totalItemCount) {
loading = false;
Log.v("...", ""+visibleItemCount);
}
}
}
Run Code Online (Sandbox Code Playgroud)
当滚动到最后,我希望在从列表顶部显示数据或滚动到列表顶部时可以看到视图我将从列表底部显示数据.
例如:
View1 View2 View3 View4 View5
View5 View1 View2 View3 View4
Seb*_*eła 68
没有办法使它无限,但有一种方法可以让它看起来像无限.
在你的适配器覆盖getCount()中返回大的东西Integer.MAX_VALUE:
@Override
public int getCount() {
return Integer.MAX_VALUE;
}
Run Code Online (Sandbox Code Playgroud)in getItem()和getView()以实数项目分数(%)的位置:
@Override
public Fragment getItem(int position) {
int positionInList = position % fragmentList.size();
return fragmentList.get(positionInList);
}
Run Code Online (Sandbox Code Playgroud)最后,将当前项目设置为中间的某个项目(否则,仅在向下方向上将是无限的).
// scroll to middle item
recyclerView.getLayoutManager().scrollToPosition(Integer.MAX_VALUE / 2);
Run Code Online (Sandbox Code Playgroud)小智 21
我发现这个问题的其他解决方案运行得很好,但我认为在回收器视图的getCount()方法中可能会有一些内存问题返回Integer.MAX_VALUE.
要解决此问题,请覆盖getItemCount()方法,如下所示:
@Override
public int getItemCount() {
return itemList == null ? 0 : itemList.size() * 2;
}
Run Code Online (Sandbox Code Playgroud)
现在,无论您使用位置从列表中获取项目,请使用以下内容
position % itemList.size()
Run Code Online (Sandbox Code Playgroud)
现在将scrollListener添加到您的回收器视图
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int firstItemVisible = linearLayoutManager.findFirstVisibleItemPosition();
if (firstItemVisible != 0 && firstItemVisible % itemList.size() == 0) {
recyclerView.getLayoutManager().scrollToPosition(0);
}
}
});
Run Code Online (Sandbox Code Playgroud)
最后要开始自动滚动,请调用以下方法
public void autoScroll() {
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
@Override
public void run() {
recyclerView.scrollBy(2, 0);
handler.postDelayed(this, 0);
}
};
handler.postDelayed(runnable, 0);
}
Run Code Online (Sandbox Code Playgroud)
Bek*_*ega 10
我创建了一个LoopingLayoutManager来解决这个问题。
它无需修改适配器即可工作,从而具有更大的灵活性和可重用性。
它功能齐全,支持:
它托管在 maven central 上,这意味着您只需要将其添加为 build.gradle 文件中的依赖项:
dependencies {
implementation 'com.github.beksomega:loopinglayout:0.3.1'
}
Run Code Online (Sandbox Code Playgroud)
并将您的更改LinearLayoutManager为LoopingLayoutManager.
它有一套 132 个单元测试,让我相信它是稳定的,但如果你发现任何错误,请在github上提出问题!
我希望这有帮助!
| 归档时间: |
|
| 查看次数: |
22082 次 |
| 最近记录: |