首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Android使用RecyclerView实现列表倒计时效果

Android使用RecyclerView实现列表倒计时效果

作者头像
SoullessCoder
发布2021-12-09 21:26:44
7890
发布2021-12-09 21:26:44
举报
文章被收录于专栏:CodeCodeCode

最近接到个需求,需要将列表中的优惠券到期时间剩余两天时,设置倒计时效果,需求到手感觉应该问题不大。

实现倒计时方法主要有两个: 1、为每个开始倒计时的item设置一个定时器,再做更新item处理; 2、只启动一个定时器,然后遍历数据,再做更新item处理。

由于之前的倒计时功能已经封装使用了CountDownTimer类,所以我这边就选用第一种方法实现,直接就开干了,一波操作下来就实现了列表的倒计时效果,下图为模拟效果的demo,非正式项目,如图所示:

实现过程还是比较顺畅的,使用CountDownTimer类也完美解决了RecyclerView中item复用导致不同条目的时间错乱的问题,本以为就这样实现了,功能来说确实算是实现了,不过当退出页面后,发现打印的log还是在跑,这就说明退出的时候我们并没有做取消处理,这就是遇到了内存的问题,那下面我们来看看是怎么解决的吧!

这里做了一个中间页面,点击按钮后跳转到倒计时页面,主要是模拟退出页面后,没有做取消处理,是否还在后台跑,下面我们看一下主要的代码。

代码实现步骤:

1、模拟数据

模拟数据用的是当前时间的后20天的数据,结构类型也是datetime类型

        //模拟数据,结构类型2021-12-11 15:28:23
        List<String> dataList = new ArrayList<>();
        //获取当前时间的月日
        Calendar now = Calendar.getInstance();
        int currentYear = now.get(Calendar.YEAR);
        int currentMonth = now.get(Calendar.MONTH) + 1;
        int currentDay = now.get(Calendar.DAY_OF_MONTH);

        for (int i = 0; i < 20; i++) {
            if ((currentDay + i) < CommonUtils.getCurrentMonthLastDay()) {
                dataList.add(currentYear + "-" + currentMonth + "-" + (currentDay + i) + " 23:59:" + i);
            } else {
                dataList.add(currentYear + "-" + (currentMonth + 1) + "-" + (currentDay + i - CommonUtils.getCurrentMonthLastDay()) + " 23:59:" + i);
            }
        }

        recycler_view.setAdapter(new TimeOutAdapter(this, dataList));

2、倒计时功能实现的TimeOutAdapter类

class TimeOutAdapter extends RecyclerView.Adapter<TimeOutAdapter.ViewHolder> {

    private Context mContext;
    private List<String> dataList;
    private SparseArray<CountDownTimerUtils> countDownMap = new SparseArray<>();

    public TimeOutAdapter(Context context, List<String> dataList) {
        this.mContext = context;
        this.dataList = dataList;
    }

    /**
     * 清空资源
     */
    public void cancelAllTimers() {
        if (countDownMap == null) {
            return;
        }
        for (int i = 0; i < countDownMap.size(); i++) {
            CountDownTimerUtils cdt = countDownMap.get(countDownMap.keyAt(i));
            if (cdt != null) {
                cdt.cancel();
            }
        }
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.time_out_view, parent, false);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {
        if (dataList != null && dataList.size() != 0) {
            holder.text_content.setText(dataList.get(position));

            try {
                //将数据转换成毫秒数,其中CommonUtils是工具类
                long residueTime = CommonUtils.residueTimeout(dataList.get(position));

                //时间大于0时设置
                if (residueTime > 0) {

                    //其中CountDownTimerUtils是倒计时的工具类
                    holder.countDownTimer = CountDownTimerUtils.getCountDownTimer()
                            .setMillisInFuture(residueTime)
                            .setCountDownInterval(1000)
                            .setTickDelegate(new CountDownTimerUtils.TickDelegate() {
                                @Override
                                public void onTick(long pMillisUntilFinished) {
                                    Log.i("TAG==", "==输出数据更新==" + pMillisUntilFinished);
                                    //更新数据
                                    holder.text_content.setText(CommonUtils.stampToDate(pMillisUntilFinished));
                                }
                            })
                            .setFinishDelegate(new CountDownTimerUtils.FinishDelegate() {
                                @Override
                                public void onFinish() {
                                    //倒计时完成
                                }
                            });

                    holder.countDownTimer.start();
                    
                    //将item的hashcode作为key设入SparseArray中
                    countDownMap.put(holder.text_content.hashCode(), holder.countDownTimer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public int getItemCount() {
        return dataList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        private final TextView text_content;
        CountDownTimerUtils countDownTimer;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            text_content = itemView.findViewById(R.id.text_content);
        }
    }
}

在这里我们可以注意到cancelAllTimer()这个方法,这就是用来解决内存的问题。

通过下面这行代码,将item中的hashcode作为key设入SparseArray中,这样在cancelAllTimer方法中可以遍历取出来进行倒计时取消操作。

countDownMap.put(holder.text_content.hashCode(), holder.countDownTimer);

3、退出页面时调用cancelAllTimer()方法取消

        //取消处理
        if (timeOutAdapter != null) {
            timeOutAdapter.cancelAllTimers();
        }

这样就可以解决这个问题啦,收工。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021/12/9 上,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档