You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Android RecyclerView中为最新条目添加持续展示5天的NEW标识

逻辑问题核心

你当前的判断逻辑仅匹配了「创建日当天」「当前日期+5天当天」两个孤立时间点,且时间阈值计算方向错误(创建日期必然早于当前时间,不可能等于你算出来的未来5天的EndDate),因此无法覆盖创建后5天的完整区间。

修正后的实现代码

直接替换你onBindViewHolder中的相关逻辑即可:

final String creationDateStr = ModelClass.getCreation_date();
// 指定Locale避免不同地区系统的日期解析异常
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);

try {
    // 解析字符串格式的创建日期为Date对象
    Date createDate = sdf.parse(creationDateStr);
    Calendar currentCal = Calendar.getInstance();
    // 当前时间往前减5天,得到NEW标签展示的最早时间阈值
    currentCal.add(Calendar.DAY_OF_MONTH, -5);
    Date showThresholdDate = currentCal.getTime();

    // 判断逻辑:创建日期在5天前至今的区间内就展示标签
    // 若需要包含5天整当天的展示,把createDate.after(showThresholdDate)替换为!createDate.before(showThresholdDate)即可
    if (createDate != null && createDate.after(showThresholdDate) && createDate.before(new Date())) {
        myViewHolder.creation_date.setVisibility(View.VISIBLE);
    } else {
        myViewHolder.creation_date.setVisibility(View.GONE);
    }
} catch (ParseException e) {
    // 日期解析异常时默认隐藏标签,避免页面崩溃
    myViewHolder.creation_date.setVisibility(View.GONE);
    e.printStackTrace();
}

补充优化建议

  • 如果你的App最低兼容版本为API 26及以上,推荐用java.time包下的LocalDate类实现,性能和可读性更好,也不存在SimpleDateFormat的线程安全问题
  • 可以把SimpleDateFormat抽成全局常量,避免每次onBindViewHolder执行时重复创建对象

内容的提问来源于stack exchange,提问作者Mediad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 13:15:03