Harmonyos5应用开发实战——优惠券卡片组件的实现
文章内容概要
本文聚焦于HarmonyOS 5应用开发中优惠券卡片组件的实现。该组件承担着展示优惠券信息、判断优惠券可用性、处理用户选择等重要功能,为用户提供清晰的优惠券展示和交互体验。
核心功能介绍
1. 优惠券信息展示
组件能够展示优惠券的关键信息,如优惠金额、使用门槛、名称、有效期等。
Column() {
Row() {
Column() {
Row() {
Text($r('app.string.currency_symbol'))
.fontColor($r('sys.color.font_on_primary'))
.fontSize($r('sys.float.Subtitle_L'))
.fontWeight(FontWeight.Medium)
.margin({ bottom: 10 })
Text(this.coupon.reduce)
.fontColor($r('sys.color.font_on_primary'))
.fontSize($r('sys.float.Display_M'))
.fontWeight(FontWeight.Medium)
.margin({ left: 4 })
}.alignItems(VerticalAlign.Bottom)
if (Number(this.coupon.full) > 0) {
Text($r('app.string.full_available', `${Number(this.coupon.full)}`))
.fontColor($r('sys.color.font_on_primary'))
.fontSize($r('sys.float.Caption_M'))
}
}
.width(100)
.height(100)
.alignItems(HorizontalAlign.Center)
.justifyContent(FlexAlign.Center)
Column() {
Text(this.coupon.name)
.fontColor($r('sys.color.font_primary'))
.fontSize($r('sys.float.Subtitle_L'))
.fontWeight(FontWeight.Medium)
.maxLines(1)
.textOverflow({ overflow: TextOverflow.Ellipsis })
Text($r('app.string.coupon_type'))
.fontColor(this.canUseCoupon() ? $r('sys.color.multi_color_09') :
$r('sys.color.font_secondary'))
.fontSize($r('sys.float.Body_S'))
.margin({ top: 2 })
Text($r('app.string.valid_until', `${this.coupon.endTime}`))
.fontColor($r('sys.color.font_secondary'))
.fontSize($r('sys.float.Caption_M'))
.margin({ top: 5 })
// ... other code
}
// ... other code
}
// ... other code
}
上述代码通过多个Text组件展示了优惠券的优惠金额、使用门槛、名称和有效期等信息,同时根据优惠券的可用性设置了不同的文字颜色。
2. 优惠券可用性判断
组件会根据优惠券的有效期和使用状态判断其是否可用。
canUseCoupon() {
if (new Date(this.coupon.endTime).getTime() > new Date().getTime() &&
this.coupon.state === CouponStateEnum.USABLE) {
return true
} else {
return false
}
}
该方法通过比较当前时间和优惠券的有效期,以及检查优惠券的状态是否为可用,来判断优惠券是否可以使用。