
一、案例介绍
本案例将展示如何使用TextTimer组件实现不同格式的时间显示。我们将创建一个支持多种时间格式切换的界面,展示TextTimer组件的格式化功能,并提供实时预览效果。
二、实现效果
- 支持多种时间格式切换
- 实时预览显示效果
- 自定义样式设置
- 动态更新时间
三、代码实现
1. 数据结构
interface FormatOption {
label: string;
value: string;
}
@Entry
@Component
struct TimeFormatter {
@State isStart: boolean = true;
@State currentFormat: string = 'HH:mm:ss';
@State fontSize: number = 40;
@State fontColor: string = '#333333';
readonly formatOptions: FormatOption[] = [
{ label: '时分秒', value: 'HH:mm:ss' },
{ label: '时分', value: 'HH:mm' },
{ label: '分秒', value: 'mm:ss' },
{ label: '带毫秒', value: 'HH:mm:ss.SSS' },
{ label: '中文格式', value: 'HH时mm分ss秒' }
];
build() {
Column() {
// 时间显示
TextTimer({
isStart: this.isStart,
count: CountType.Countup,
format: this.currentFormat
})
.fontSize(this.fontSize)
.fontColor(this.fontColor)
.margin({ bottom: 40 })
// 格式选择
Text('选择时间格式')
.fontSize(16)
.fontColor('#666666')
.margin({ bottom: 10 })
Flex({ wrap: FlexWrap.Wrap, justifyContent: FlexAlign.Center }) {
ForEach(this.formatOptions, (option: FormatOption) => {
Button(option.label)
.margin(5)
.backgroundColor(this.currentFormat === option.value ? '#007DFF' : '#F5F5F5')
.fontColor(this.currentFormat === option.value ? '#FFFFFF' : '#333333')
.onClick(() => {
this.currentFormat = option.value;
})
})
}
.margin({ bottom: 40 })
// 样式设置
Column({ space: 20 }) {
Text('自定义样式')
.fontSize(16)
.fontColor('#666666')
Row({ space: 10 }) {
Text('字体大小:')
.fontSize(14)
Counter() {
Text(`${this.fontSize}`)
}
.onInc(() => {
if (this.fontSize < 100) {
this.fontSize += 2;
}
})
.onDec(() => {
if (this.fontSize > 20) {
this.fontSize -= 2;
}
})
}
Row({ space: 10 }) {
Text('字体颜色:')
.fontSize(14)
Select([
{ value: '#333333', label: '深灰' },
{ value: '#007DFF', label: '蓝色' },
{ value: '#FF0000', label: '红色' },
{ value: '#00CC00', label: '绿色' }
])
.selected(0)
.value(this.fontColor)
.onSelect((index: number, value: string) => {
this.fontColor = value;
})
}
}
.width('100%')
.padding({ left: 20, right: 20 })
}
.width('100%')
.height('100%')
.padding(20)
}
}
四、关键点解析
1. 格式定义
- 预设多种时间格式
- 支持自定义分隔符
- 灵活的格式切换
2. 样式控制
- 字体大小调节
- 颜色选择功能
- 实时预览效果
3. 交互设计
- 格式选择按钮
- 样式调节控件
- 状态即时更新
五、总结
本案例通过HarmonyOS NEXT的TextTimer组件实现了多种时间格式的动态显示和自定义样式设置。通过预设多种时间格式和灵活的样式控制,用户可以方便地切换和调整时间显示效果。案例展示了TextTimer组件在格式化显示方面的强大功能,适合开发者学习和应用到实际项目中。

被折叠的 条评论
为什么被折叠?



