android - RecyclerView auto scroll item one by one
问题描述
I have a RecyclerView
in my activity. Can I programmatically scroll my RecyclerView
items one at a time (like the animation effect on a carousel) ? I have some code below but i don’t know how to make the effect. Any suggestions are welcomed!
RandomProductAdapter randomProductAdapter = new RandomProductAdapter(this.mContext, randomProductList);
random_rv.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
random_rv.setAdapter(randomProductAdapter);
random_rv.smoothScrollToPosition(randomProductAdapter.getItemCount()-1);
解决方案
Thanks for help in the comments. I try applying some of the logic using a Thread but my app keep crashing. So i found my solution here and here also
first create runnable:
final int duration = 10;
final int pixelsToMove = 30;
private final Handler mHandler = new Handler(Looper.getMainLooper());
private final Runnable SCROLLING_RUNNABLE = new Runnable() {
@Override
public void run() {
recyclerView.smoothScrollBy(pixelsToMove, 0);
mHandler.postDelayed(this, duration);
}
};
then after setadapter() to the recyclerView use following:
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int lastItem = layoutManager.findLastCompletelyVisibleItemPosition();
if(lastItem == layoutManager.getItemCount()-1){
mHandler.removeCallbacks(SCROLLING_RUNNABLE);
Handler postHandler = new Handler();
postHandler.postDelayed(new Runnable() {
@Override
public void run() {
recyclerView.setAdapter(null);
recyclerView.setAdapter(madapter);
mHandler.postDelayed(SCROLLING_RUNNABLE, 2000);
}
}, 2000);
}
}
});
mHandler.postDelayed(SCROLLING_RUNNABLE, 2000);
推荐阅读
- python - 如何在 Python 中一次保存多个数据
- vue.js - 可能使用插槽将值从父级传递给子级
- javascript - VueJS子到父隐藏组件的布尔值
- bash - 从终端打开 Firefox-bin 文件时打印 Firefox 日志消息?
- angular - 如何在 Angular 7 中使用 keycloak 时保持会话活跃?
- vue.js - 如果 URL 端点有句点 (.) 则无法访问 vuejs 路由
- django - django rest框架无法从字符串值序列化外键字段
- python - 在 python 中使用 Tkinter 在井字游戏中的 minimax 算法有什么问题?
- java - 如何在 RecyclerView 上展示插页式广告,
- azure-cognitive-services - 选择标记识别的 ETA?