首页 > 解决方案 > 用动态创建突破性的新标题

问题描述

我正在创建一个突发新闻应用程序,我想无限滚动 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);

任何帮助都会更有帮助

标签: javaandroidandroid-recyclerviewautoscroll

解决方案


这是一个没有任何侦听器或程序化滚动的解决方案。

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 中)。


推荐阅读