Demonic218
Demonic218

Reputation: 923

Automatic RecyclerView scrolling

I'm trying to implement a banner in my app that works similar to how a an advertising banner works, where every few seconds it would scroll to the next ad. I wanted it to be dynamic so I used a RecyclerView, I've got it horizontal using the snap helper for a nice effect. However it's the automatic scrolling I'm struggling with, I need it to scroll to the next card after a few seconds and when it reaches the end scroll back to the first and start over.

I have also seen people talk of a viewflipper for this but I've never used one and not sure if it will give the desired effect.

Upvotes: 3

Views: 4630

Answers (2)

Demonic218
Demonic218

Reputation: 923

So I've tried many approaches to solve this, Firstly, I tried @Ganesh's answer which I modified to get working. For those interested here is what I did,

Firstly created a timer object, as well as scheduled the timer task I created with a delay.

Blockquote

timer.scheduleAtFixedRate(new AutoScrollTask(), 2000, 5000);

The timer task uses the arraylist to work out it's current position and when it reaches the end it simply goes in reserve, to avoid that sudden jump to the first item.

private class AutoScrollTask extends TimerTask{
        @Override
        public void run() {
            if(position == arrayList.size() -1){
                end = true;
            } else if (position == 0) {
                end = false;
            }
            if(!end){
                position++;
            } else {
                position--;
            }
            recyclerView.smoothScrollToPosition(position);
        }
    }

This method does have it's flaws which I why I took @Tam Huynh's advice and researched the ViewFlipper. In this case however I used an AdapterViewFlipper. This allowed me to build a custom adapter where I could dynamically add views based on what data I was receiving.

Upvotes: 1

Ganesh
Ganesh

Reputation: 376

First, Create A TimerTask class like this,

  private class ScrollTask extends TimerTask {
                public void run() {
                recyclerview.post(new Runnable() {
                    public void run() {

                        int nextView = (adapter.getAdapterPosition() + 1) % adapter.getItemCount()

                       recyclerView.smoothScrollToPosition(nextView);    
                    }
                });
            }
        }

Then create a timer object

Timer timer = new Timer();

and Schedule the task like this,

timer.schedule(new ScrollTask(), interval // delay before task is to be executed,
 interval //period between successive task executions.)

interval is integer containing time in milliseconds

Upvotes: 1

Related Questions