java - 用动态创建突破性的新标题
问题描述
我正在创建一个突发新闻应用程序,我想无限滚动 recyclerview,但它在列表大小完成后结束,所以如何自动滚动 recyclerview。
通过这种方法,自动滚动完成,但它不是无限滚动
public void autoScrollAnother() {
scrollCount = 0;
final int speedScroll = 1200;
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
@Override
public void run() {
if(scrollCount == breakingNewAdapter.getItemCount()){
breakingNewAdapter.notifyDataSetChanged();
}
brakingNews.smoothScrollToPosition((scrollCount++));
handler.postDelayed(this, speedScroll);
}
};
handler.postDelayed(runnable, speedScroll);
}
并像这样设置在recyclerview中
layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
brakingNews.setLayoutManager(layoutManager);
brakingNews.setHasFixedSize(true);
brakingNews.setItemViewCacheSize(10);
brakingNews.setDrawingCacheEnabled(true);
brakingNews.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_LOW);
brakingNews.setAdapter(breakingNewAdapter);
任何帮助都会更有帮助
解决方案
这是一个没有任何侦听器或程序化滚动的解决方案。
getItemCount
当用户到达列表末尾时增加返回值。您的实际列表大小并不重要,只是您将每次调用都onBindViewHolder
指向特定项目。
试试这个代码:
public class BreakingNewsAdapter {
private List<BreakingNews> news;
private int adapterSize = 0;
public void setNews(List<BreakingNews> news) {
this.news = news;
this.adapterSize = news.size(); // some initialization
notifyDataSetChanged();
}
@Override
public int getItemCount() {
if (this.news != null)
return this.adapterSize;
return 0;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
BreakingNews item = news.get(position % news.size()); // the '%' will ensure you'll always have data to bind to the view holder
if (position == this.adapterSize - 1) {
this.adapterSize += news.size(); // do whatever you want here, just make sure to increment this.adapterSize's value
new Handler().postDelayed(() -> notifyItemInserted(position + 1), 100); // Can't notify directly from this method, so we use a Handler. May change the delay value for what works best for you.
// notifyItemInserted will animate insertion of one item to your list. You may call to notifyDataSetChanged or notifyItemRangeInserted if you don't want the animation
//new Handler().postDelayed(() -> notifyItemRangeInserted(position + 1, this.adapterSize - news.size()), 100);
//new Handler().postDelayed(this::notifyDataSetChanged, 100);
}
}
}
您可能会注意到,当您到达列表末尾时,滚动将停止,您需要再次滚动。
如果您根本不希望滚动停止,您可以adapterSize
使用一个非常大的数字进行初始化,缺点是滚动条不会移动。
另一种选择是检查之前的值this.adapterSize - 1
。
this.adapterSize - (news.size() / 2)
例如。这样,滚动将停止片刻,然后自动继续。
这里有很多选项,因此您可以使用数字(可能初始化adapterSize
为输入大小的两倍等),但主要规则是检测特定事件onBindViewHilder
并增加适配器的大小。
另请参阅h22 的答案。
如果您有兴趣,可以找到一些实现不同方法的文章(在 kotlin 中)。
推荐阅读
- c# - 带有 Faye Ruby 客户端的 AspNet SignalR Hub
- flutter - 颤振边界半径方面
- arrays - NumPy 将负值更改为零以及列中高于它的所有值
- python - 布尔表达式比较中的python优先级
- javascript - web3 [object, Promise] 错误,.then 和 await 不起作用
- python - python中价格预测的滑动窗口
- excel - 试图找到包含日期的相应单元格范围的值,但只对日期感兴趣的是今天
- next.js - 子蛞蝓的不同模板
- ios - iOS ResearchKit Unrecognized selector sent to instance 错误
- c# - 为什么我的角色每次不动时只向目标旋转一次?