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

如何在新版Android Studio中为CalendarView高亮特定日期?

最新Android日历视图实现方案

方案一:使用官方维护的AndroidX组件

优先选择androidx.appcompat.widget.CalendarView,该组件属于AndroidX生态,持续适配最新Android Studio版本和系统API,无需额外第三方依赖。

布局示例

<androidx.appcompat.widget.CalendarView
    android:id="@+id/calendarView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:firstDayOfWeek="2" <!-- 可选:设置周一为一周第一天 -->
    android:dateTextAppearance="@style/CalendarDateStyle"
    android:weekDayTextAppearance="@style/CalendarWeekStyle"/>

代码逻辑(Kotlin)

val calendarView = findViewById<CalendarView>(R.id.calendarView)
calendarView.setOnDateChangeListener { view, year, month, dayOfMonth ->
    val selectedDate = "${year}-${String.format("%02d", month + 1)}-${String.format("%02d", dayOfMonth)}"
    // 处理选中日期的业务逻辑
}

方案二:基于RecyclerView自定义实现

如果官方组件无法满足定制化需求(比如特殊日期标记、自定义样式),可以基于RecyclerView从零实现,完全适配最新开发环境:

  • 创建日期数据类,包含日期值、是否为当月日期、是否选中、是否有标记等属性
  • 使用GridLayoutManager(列数设为7)作为RecyclerView的布局管理器
  • 编写Adapter,绑定日期数据并处理点击事件
  • 实现月份切换逻辑:计算每月第一天的星期数,填充前后月份的补位日期,保证日历网格完整

方案三:修复第三方依赖兼容性问题

若之前使用的material-calendar-view失效,检查依赖版本是否适配最新Android Gradle Plugin(AGP):

  1. 确保项目使用最新的AGP稳定版(当前为8.x系列)
  2. 更新依赖到兼容版本,示例:
implementation 'com.prolificinteractive:material-calendarview:2.0.1'

若仍有问题,替换为Material Design 3官方组件,使用DatePickerDialog或其内嵌的日历视图,依赖如下:

implementation 'com.google.android.material:material:1.11.0'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 23:20:45