HarmonyOS应用开发实战:小事记 - 日历组件手写实现:Grid 构建日期网格与事件标记点

📅 2026/7/20 16:07:10 👁️ 阅读次数 📝 编程学习
HarmonyOS应用开发实战:小事记 - 日历组件手写实现:Grid 构建日期网格与事件标记点

前言

日历组件是许多应用中的核心 UI 元素。在小事记(xiaoshiji_ohos_app) 的CalendarViewPage.ets中,使用 Grid 手写实现了一个完整的日历组件,包括日期网格、事件标记点、日期选中状态和月份切换功能。本文深入解析日历组件的实现原理和关键代码。

本文参考 HarmonyOS 官方文档:Grid 组件 和 日期计算。

一、日历组件的核心逻辑

1.1 日期计算

// 日期计算工具函数 function getDaysInMonth(year: number, month: number): number { return new Date(year, month, 0).getDate(); } function getFirstDayOfMonth(year: number, month: number): number { return new Date(year, month - 1, 1).getDay(); } function generateCalendarDays(year: number, month: number): number[] { const daysInMonth = getDaysInMonth(year, month); const firstDay = getFirstDayOfMonth(year, month); const days: number[] = []; // 填充前导空白 for (let i = 0; i < firstDay; i++) { days.push(0); } // 填充日期 for (let i = 1; i <= daysInMonth; i++) { days.push(i); } // 填充尾部空白(补齐到 6 行 = 42 格) while (days.length < 42) { days.push(0); } return days; }
方案适用场景注意事项
方案一简单场景实现简单,易于维护
方案二复杂场景灵活性高,需注意性能
方案三特殊场景针对特定需求优化

二、日历的完整实现

2.1 日历组件

// CalendarViewPage.ets — 完整日历组件 @Entry @Component export struct CalendarViewPage { @State currentMonth: number = 5; @State currentYear: number = 2024; @State selectedDay: number = 20; @State events: CalendarEvent[] = getMockCalendarEvents(); private weekDays: string[] = ['日', '一', '二', '三', '四', '五', '六']; private eventDays: number[] = [1, 12, 20]; get calendarDays(): number[] { return generateCalendarDays(this.currentYear, this.currentMonth); } build() { Column() { // 月份导航 this.buildMonthHeader() // 星期标题 this.buildWeekHeader() // 日期网格 this.buildCalendarGrid() // 事件列表 this.buildEventList() } .width('100%') .height('100%') .backgroundColor(Color.White) } @Builder buildMonthHeader() { Row() { Text('<') .fontSize(20) .fontColor('#1A1A2E') .onClick(() => { this.previousMonth(); }) Blank() Text(`${this.currentYear}年${this.currentMonth}月`) .fontSize(18) .fontWeight(FontWeight.Bold) Blank() Text('>') .fontSize(20) .fontColor('#1A1A2E') .onClick(() => { this.nextMonth(); }) } .width('100%') .padding({ left: 20, right: 20, top: 10, bottom: 10 }) } @Builder buildWeekHeader() { Row() { ForEach(this.weekDays, (day: string) => { Text(day) .fontSize(13) .fontColor('#9CA3AF') .width('14.28%') .textAlign(TextAlign.Center) }, (day: string) => day) } .width('100%') .padding({ top: 8, bottom: 8 }) } @Builder buildCalendarGrid() { Grid() { ForEach(this.calendarDays, (day: number, index: number) => { GridItem() { if (day > 0) { Column() { Text(day.toString()) .fontSize(15) .fontColor(this.selectedDay === day ? Color.White : '#1A1A2E') .fontWeight(this.selectedDay === day ? FontWeight.Bold : FontWeight.Normal) if (this.eventDays.includes(day)) { Circle().width(4).height(4).fill('#7B68EE').margin({ top: 2 }) } } .width(40) .height(40) .justifyContent(FlexAlign.Center) .backgroundColor(this.selectedDay === day ? '#7B68EE' : Color.Transparent) .borderRadius(20) .onClick(() => { this.selectedDay = day; }) } } }, (day: number, index: number) => `${index}`) } .columnsTemplate('1fr 1fr 1fr 1fr 1fr 1fr 1fr') .rowsGap(4) .width('100%') .padding({ left: 8, right: 8 }) } @Builder buildEventList() { Column({ space: 0 }) { ForEach(this.events, (event: CalendarEvent) => { Row() { Text(event.date.split('-')[2]) .fontSize(14) .fontColor('#7B68EE') .width(40) .fontWeight(FontWeight.Bold) Column({ space: 2 }) { Text(event.title).fontSize(15).fontColor('#1A1A2E') Text(event.time).fontSize(12).fontColor('#9CA3AF') } .margin({ left: 12 }) .layoutWeight(1) } .width('100%') .padding({ left: 20, right: 20, top: 12, bottom: 12 }) }, (event: CalendarEvent) => event.id) } .width('100%') .layoutWeight(1) } private previousMonth(): void { if (this.currentMonth === 1) { this.currentMonth = 12; this.currentYear--; } else { this.currentMonth--; } } private nextMonth(): void { if (this.currentMonth === 12) { this.currentMonth = 1; this.currentYear++; } else { this.currentMonth++; } } }

三、事件标记点

3.1 标记点的实现

// 事件标记点的实现 if (this.eventDays.includes(day)) { Circle() .width(4) .height(4) .fill('#7B68EE') // 紫色标记点 .margin({ top: 2 }) }

3.2 标记点的样式

属性说明
颜色#7B68EE紫色,与主题色一致
大小4x4小巧,不干扰日期显示
位置日期下方 2vp与日期文字保持距离

四、常见问题

4.1 日期计算错误

问题getDaysInMonth返回的天数不正确。

解决方案:使用new Date(year, month, 0)获取当月的最后一天。

4.2 网格对齐问题

问题:日期网格与星期标题未对齐。

解决方案:确保两者使用相同的宽度分配方式。

五、

// 异步操作示例 async function handleAsync(): Promise<void> { try { const result = await this.loadData(); this.data = result; } catch (err) { console.error("加载失败", err); } }

扩展功能

5.1 月份切换动画

// 月份切换动画 private async switchMonth(forward: boolean): Promise<void> { animateTo({ duration: 200 }, () => { if (forward) { this.nextMonth(); } else { this.previousMonth(); } }); }

八、拓展阅读

本节汇总了与本文主题相关的扩展阅读材料,帮助读者深入理解相关技术细节。

8.1 官方文档

  • 开发者指南:HarmonyOS 应用开发概述
  • API 参考:ArkTS API 参考

8.2 相关技术文章

  • 性能优化最佳实践
  • 常见问题排查指南

8.3 社区资源

  • 开源鸿蒙跨平台社区:https://openharmonycrossplatform.csdn.net

十、最佳实践与优化建议

在实际开发中,合理运用上述技术可以显著提升应用的性能和用户体验。以下是几个关键的最佳实践建议:

10.1 性能优化要点

优化方向具体措施预期效果
渲染性能减少不必要的组件重建提升帧率
内存管理及时释放不再使用的资源降低内存占用
响应速度避免在主线程执行耗时操作提升交互流畅度

10.2 推荐实践步骤

按照以下步骤进行优化:

  1. 使用 DevEco Studio 的 Profiler 工具分析当前性能瓶颈
  2. 针对识别出的热点进行针对性优化
  3. 通过单元测试和集成测试验证优化效果
  4. 在真机环境下进行回归测试

10.3 代码示例

// 推荐的最佳实践示例 @Component export struct OptimizedComponent { // 使用 @State 管理最小粒度的状态 @State private isActive: boolean = false; build() { Column() { Text(this.isActive ? '激活' : '未激活') .fontSize(16) } .onClick(() => { // 使用 animateTo 实现平滑过渡 animateTo({ duration: 300 }, () => { this.isActive = !this.isActive; }); }); } }

最佳实践提示:在编写代码时,始终遵循 ArkUI 的性能优化原则,避免在 build() 方法中执行复杂计算或频繁的状态更新。

总结

// 类型定义示例 interface ApiResponse<T> { code: number; message: string; data: T; } async function fetchData<T>(url: string): Promise<ApiResponse<T>> { const response = await fetch(url); return response.json(); }

本文深入解析了日历组件的手写实现。核心要点如下:

  1. 日期计算:使用getDaysInMonthgetFirstDayOfMonth计算日期
  2. Grid 网格:7列等宽布局,40x40 的日期格子
  3. 事件标记点:4x4 的紫色圆点标记有事件的日期
  4. 月份切换:通过修改currentMonthcurrentYear实现月份切换

如果这篇文章对你有帮助,欢迎点赞👍、收藏⭐、关注🔔,你的支持是我持续创作的动力!


九、完整示例代码

9.1 完整组件实现

以下是一个完整的组件实现示例,展示了本文介绍的各个技术点的综合运用:

import { Component, State, Prop } from '@kit.ArkUI'; @Component export struct DemoComponent { @Prop title: string = ''; @State count: number = 0; build() { Column({ space: 12 }) { // 标题区域 Text(this.title) .fontSize(18) .fontWeight(FontWeight.Bold) .fontColor('#1A1A2E') .width('100%') // 内容区域 Text(`当前计数: ${this.count}`) .fontSize(14) .fontColor('#6B7280') // 交互按钮 Button('点击增加') .width(120) .height(40) .backgroundColor('#7B68EE') .borderRadius(20) .fontColor(Color.White) .onClick(() => { this.count++; }) } .width('100%') .padding(16) .backgroundColor(Color.White) .borderRadius(12) .shadow({ radius: 4, color: '#00000008', offsetX: 0, offsetY: 2 }) } }

9.2 使用方式

在页面中引入并使用该组件:

@Entry @Component struct Index { build() { Column() { DemoComponent({ title: '示例组件' }) } .width('100%') .height('100%') .backgroundColor('#F8F9FA') } }

9.3 代码说明

  • 组件封装:使用@Component装饰器定义可复用的组件
  • 状态管理:使用@State管理组件内部状态
  • 参数传递:使用@Prop接收外部传入的参数
  • 事件处理:使用onClick处理用户交互
  • 样式优化:使用borderRadiusshadow等属性美化 UI

相关资源:

  • 官方文档 - 开发者指南:HarmonyOS 应用开发
  • 官方文档 - ArkUI 组件参考:ArkUI 组件
  • 官方文档 - API 参考:API 参考
  • 官方文档 - 状态管理:状态管理概述
  • 官方文档 - 动画:动画概述
  • 官方文档 - 网络管理:网络管理
  • 官方文档 - 数据管理:数据管理
  • 开源鸿蒙跨平台社区:https://openharmonycrossplatform.csdn.net