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

Kotlin中MaterialCalendarView标题格式化后切换不更新问题

MaterialCalendarView切换月份时标题不更新的解决办法

问题出在你设置标题格式化器的逻辑上:你提前将当前时间格式化为固定的字符串date,之后每次标题需要更新时,都直接返回这个固定值,自然不会随月份切换变化。

正确的做法是利用setTitleFormatter提供的CalendarDay参数,基于当前显示的月份日期来动态生成标题文本,修改后的代码如下:

方案1(使用SimpleDateFormat)

val pattern = "MMM,yyyy"
val simpleDateFormat = SimpleDateFormat(pattern)

calendarView.apply {
    setTitleFormatter { day ->
        val calendar = Calendar.getInstance().apply {
            set(day.year, day.month, day.day)
        }
        simpleDateFormat.format(calendar.time)
    }
}

方案2(使用Java 8+ DateTimeFormatter,更简洁)

如果项目支持Java 8及以上特性,推荐使用更现代的日期API:

val formatter = DateTimeFormatter.ofPattern("MMM,yyyy", Locale.getDefault())

calendarView.setTitleFormatter { day ->
    // MaterialCalendarView的month从0开始,LocalDate的月份从1开始,所以要+1
    LocalDate.of(day.year, day.month + 1, day.day).format(formatter)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 10:55:15