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

Android CalendarView返回Activity后恢复选中日期的实现方法

如何恢复CalendarView之前选中的日期

当然可以恢复之前选中的日期!这个问题在Android开发里挺常见的,核心就是提前保存用户选中的日期状态,然后在Activity回到前台时把这个状态恢复回去就行。下面给你一步步的具体实现方案:

1. 定义变量存储选中的日期

在你的原Activity里,先声明一个变量来保存用户选中的日期毫秒值,默认可以设为当前时间:

private long selectedDate = System.currentTimeMillis();
private CalendarView calendarView;

2. 监听日期选择事件,更新存储的日期

给CalendarView设置日期改变的监听器,每当用户选中新的日期,就把这个日期的毫秒值存到我们定义的变量里:

calendarView.setOnDateChangeListener((view, year, month, dayOfMonth) -> {
    // 注意:Calendar的月份是从0开始的,要和CalendarView返回的month对应
    Calendar calendar = Calendar.getInstance();
    calendar.set(year, month, dayOfMonth);
    selectedDate = calendar.getTimeInMillis();
});

3. 保存状态,防止Activity被系统回收时丢失数据

Android系统可能会在后台回收Activity,这时候我们存的变量值会丢失,所以要重写onSaveInstanceState方法,把选中日期存入Bundle:

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putLong("SELECTED_DATE_KEY", selectedDate);
}

然后在onCreate方法里,恢复这个保存的日期:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_activity_layout);
    calendarView = findViewById(R.id.your_calendar_view_id);

    if (savedInstanceState != null) {
        // 从Bundle里取出之前保存的日期,默认值设为当前时间
        selectedDate = savedInstanceState.getLong("SELECTED_DATE_KEY", System.currentTimeMillis());
        // 恢复CalendarView的选中状态
        // 第三个参数设为false,避免重复触发日期改变监听
        calendarView.setDate(selectedDate, true, false);
    } else {
        // 首次启动时,设置默认选中当前日期
        calendarView.setDate(selectedDate, true, false);
    }
}

4. 从详情页返回时,确保日期恢复

当你启动详情Activity后,原Activity会进入暂停状态,返回时会执行onResume方法。我们可以在这里再设置一次选中日期,保证每次回到原页面都能正确恢复:

@Override
protected void onResume() {
    super.onResume();
    // 恢复选中日期,动画过渡可选,这里设为true提升体验
    calendarView.setDate(selectedDate, true, false);
}

小提示

  • 如果你的事件加载逻辑是绑定在CalendarView的日期改变监听里的,恢复日期时第三个参数设为false可以避免重复加载事件,减少不必要的操作;
  • 处理日期时要注意Calendar类的月份是0起始的,和CalendarView返回的month参数一致,不用额外加1;
  • 如果你需要持久化这个选中日期(比如重启App后也能恢复),可以把selectedDate存入SharedPreferences,在onCreate时从SharedPreferences读取即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 04:13:01