Multiple count down timers in RecyclerView flickering when scrolled

前端 未结 3 1413
孤街浪徒
孤街浪徒 2020-11-30 09:27

I have implemented count down timer for each item of RecyclerView which is in a fragment activity. The count down timer shows the time remaining for expiry. The count down t

3条回答
  •  春和景丽
    2020-11-30 09:44

    This problem is simple.

    RecyclerView reuses the holders, calling bind each time to update the data in them.

    Since you create a CountDownTimer each time any data is bound, you will end up with multiple timers updating the same ViewHolder.

    The best thing here would be to move the CountDownTimer in the FeedViewHolder as a reference, cancel it before binding the data (if started) and rescheduling to the desired duration.

    public void onBindViewHolder(final FeedViewHolder holder, final int position) {
        ...
        if (holder.timer != null) {
            holder.timer.cancel();
        }
        holder.timer = new CountDownTimer(expiryTime, 500) {
            ...
        }.start();
    }
    
    public static class FeedViewHolder extends RecyclerView.ViewHolder {
        ...
        CountDownTimer timer;
    
        public FeedViewHolder(View itemView) {
            ...
        }
    }
    

    This way you will cancel any current timer instance for that ViewHolder prior to starting another timer.

提交回复
热议问题