首页 > 解决方案 > 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);

标签: androidandroid-recyclerviewcarousel

解决方案


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);

推荐阅读