#跟着晓明学鸿蒙# 标签云的基础布局实现
·

目录
- 案例介绍
- 代码实现
- 代码详解
- 数据结构设计
- 界面布局实现
- 总结
案例介绍
标签云是一种常见的UI模式,用于展示一组关键词或标签,通常用于分类、筛选或导航。本案例将实现一个基础的标签云布局,展示如何使用Flow和FlowItem组件创建自适应的标签布局。
代码实现
@Entry
@Component
struct InterestTagsPage {
@State categories: Array<{name: string, tags: Array<{name: string, selected: boolean}>}> = [
{
name: '影视',
tags: [
{ name: '动作', selected: false },
{ name: '喜剧', selected: false },
{ name: '科幻', selected: false },
{ name: '悬疑', selected: false },
{ name: '动画', selected: false },
{ name: '纪录片', selected: false },
{ name: '剧情', selected: false },
{ name: '恐怖', selected: false }
]
}
]
build() {
Column() {
// 顶部标题
Text('选择您感兴趣的标签')
.fontSize(22)
.fontWeight(FontWeight.Bold)
.margin({ top: 20, bottom: 10 })
// 说明文字
Text('这将帮助我们为您推荐更符合您口味的内容')
.fontSize(14)
.fontColor('#666666')
.margin({ bottom: 30 })
// 标签分类列表
Scroll() {
Column() {
ForEach(this.categories, (category, categoryIndex) => {
// 分类标题
Text(category.name)
.fontSize(18)
.fontWeight(FontWeight.Medium)
.margin({ top: 20, bottom: 10 })
.alignSelf(ItemAlign.Start)
// 标签云
Flow() {
ForEach(category.tags, (tag, tagIndex) => {
FlowItem() {
Text(tag.name)
.fontSize(14)
.fontColor(tag.selected ? Color.White : '#333333')
.backgroundColor(tag.selected ? '#FF6B00' : '#F0F0F0')
.height(36)
.padding({ left: 15, right: 15 })
.borderRadius(18)
.onClick(() => {
// 更新标签选中状态
this.categories[categoryIndex].tags[tagIndex].selected = !tag.selected
})
}
.margin(8)
})
}
.width('100%')
})
}
.width('100%')
.padding({ left: 15, right: 15 })
}
.width('100%')
.layoutWeight(1)
}
.width('100%')
.height('100%')
.backgroundColor('#F5F5F5')
}
}
代码详解
数据结构设计
- 使用
@State装饰器定义分类和标签数据:@State categories: Array<{name: string, tags: Array<{name: string, selected: boolean}>}>- categories是一个数组,每个元素包含分类名称和该分类下的标签数组
- 每个标签包含名称和选中状态两个属性
界面布局实现
根容器使用Column布局,设置全屏显示和背景色:
Column() .width('100%') .height('100%') .backgroundColor('#F5F5F5')顶部标题和说明文字的样式设置:
Text('选择您感兴趣的标签') .fontSize(22) .fontWeight(FontWeight.Bold) .margin({ top: 20, bottom: 10 })标签云的核心实现:
Flow() { ForEach(category.tags, (tag, tagIndex) => { FlowItem() { Text(tag.name) .fontSize(14) .fontColor(tag.selected ? Color.White : '#333333') .backgroundColor(tag.selected ? '#FF6B00' : '#F0F0F0') .height(36) .padding({ left: 15, right: 15 }) .borderRadius(18) } .margin(8) }) } .width('100%')- 使用Flow作为容器,实现流式布局
- 每个标签使用FlowItem包装,确保自动换行
- 标签样式包括字体大小、颜色、背景色、高度、内边距和圆角
- 通过margin控制标签之间的间距
交互实现:
.onClick(() => { this.categories[categoryIndex].tags[tagIndex].selected = !tag.selected })- 点击标签时切换选中状态
- 选中状态通过不同的文字颜色和背景色展示
总结
本案例展示了如何使用Flow和FlowItem组件实现基础的标签云布局。通过合理的数据结构设计和样式设置,实现了标签的自动换行和对齐。Flow组件的流式布局特性很好地解决了标签长度不一的布局问题,而FlowItem组件则确保了每个标签都能正确地参与布局。
更多推荐

所有评论(0)