2

I'm creating a horizontal recycler view that scrolls automatically after a certain time (Say 5 seconds). I used countdowntimer. But, it is not working as expected. the timer is not running properly. Some times it jumps two or more recycler items at a time.

here is my code:

class StoryViewHolder extends RecyclerView.ViewHolder {
{
CountDownTimer timer;
....
}
public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder, final int position) {
{
.....
if (holder.timer != null) {
            holder.timer.cancel();
        }

        holder.timer = new CountDownTimer(5000, 1000) {
            @Override
            public void onTick(long timeLeft) {

            }

            @Override
            public void onFinish() {
                StoryFragment.scrollToPosition((position+1));
            }
        };
        holder.timer.start();
}

My question is similar to this question. But the answer they said is not working. Set counter inside RecyclerView

Hope someone will help. Thankyou. }

1 Answers1

2

I would suggest moving your CountDownTimer outside of your ViewHolder. Your ViewHolder is usually just for rendering that item within your RecyclerView. It's not a good idea to have it doing more than one thing, such as handling it's list's scroll.

I would move it into your StoryFragment, this will allow you to clean up your timer based on the Android lifecycle, such as stopping it when the app is put into the background, and restarting it when it comes back into view. Doing this in onResume and onPause would be a great idea.

Also, you should change to a normal Timer, instead of a CountDownTimer, set your interval to 5 seconds, and then every onTick, scroll your list over one item.

advice
  • 5,778
  • 10
  • 33
  • 60
  • why do i take normal timer instead of countdowntimer? –  Jul 31 '18 at 04:58
  • If I did as you said, I can't able to show the progress bar for each view in my recycler view. Just like in WhatsApp status, Instagram stories.. –  Jul 31 '18 at 05:12
  • Thankyou very much. Your idea is working well with countdowntimer. –  Jul 31 '18 at 08:52