多个倒计时器在回收器视图中同时结束

时间:2018-05-07 06:24:35

标签: android listview android-recyclerview runnable countdowntimer

我有一个回收者视图,其中每个项目都有倒计时器,并且可能有多个倒计时器同时结束。我想要做的是在计时器结束时删除项目。如果只有一个项目,那么代码可以正常工作,但是当有多个项目时,它会因indexoutofbounds异常而崩溃。我尝试了堆栈溢出时提到的不同解决方案,但它们似乎都没有帮助我删除视图。

这是我的适配器代码。

public class UpcomingContestRecyclerAdapter extends RecyclerView.Adapter<UpcomingContestRecyclerAdapter.ViewHolder> {

private Context context;
private ArrayList<LiveAndUpcomingContest> live_and_upcoming_contest;
private Activity activity;

//Constructor
public UpcomingContestRecyclerAdapter(Activity context, ArrayList<LiveAndUpcomingContest> live_and_upcoming_contest) {
    // TODO Auto-generated constructor stub
    this.context = context;
    this.live_and_upcoming_contest = live_and_upcoming_contest;
    this.activity = context;
}


@Override
public UpcomingContestRecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.upcoming_contests_list_item, viewGroup, false);
    return new ViewHolder(view);
}

// Initialize the viewholder class.
public class ViewHolder extends RecyclerView.ViewHolder{
    CountDownTimer timer;
    private TextView game_countdown;

 public ViewHolder(View view) {
        super(view);
        game_countdown = view.findViewById(R.id.game_countdown);
}
}

@Override
public void onBindViewHolder(final UpcomingContestRecyclerAdapter.ViewHolder viewHolder, final int position) {

    if(viewHolder.timer!= null)
    {
        viewHolder.timer.cancel();

    }
    //Start countdown timer on the game countdown view.
    viewHolder.timer = new CountDownTimer(live_and_upcoming_contest.get(position).getStart_time(), 500) {
        public void onTick(long millisUntilFinished) {
            long secondsInMilli = 1000;
            long minutesInMilli = secondsInMilli * 60;
            long hoursInMilli = minutesInMilli * 60;

            long elapsedHours = millisUntilFinished / hoursInMilli;
            millisUntilFinished = millisUntilFinished % hoursInMilli;

            long elapsedMinutes = millisUntilFinished / minutesInMilli;
            millisUntilFinished = millisUntilFinished % minutesInMilli;

            long elapsedSeconds = millisUntilFinished / secondsInMilli;

            String yy = String.format("%02d:%02d:%02d", elapsedHours, elapsedMinutes, elapsedSeconds);
            viewHolder.game_countdown.setText(yy);
        }

        public void onFinish() {
            viewHolder.game_countdown.setText("00:00:00");
            live_and_upcoming_contest.remove(position);
            notifyDataSetChanged();
        }
    }.start();
}

这可能不是正确的方法,因为我不应该每次都在onBindViewHolder上启动一个新的计时器。我发现堆栈上的代码溢出来取消视图持有者onBindViewHolder之前开始一个新的但不起作用。我尝试了一个使用处理程序的解决方案,并且作为计时器工作正常,但即使在删除项目时,它也崩溃了。为了再次澄清,将会有多个计时器同时结束,因此同时删除多个列表项,代码应该能够处理它。

感谢任何帮助。谢谢。

0 个答案:

没有答案