HarmonyOS鸿蒙Next中Waterflow组件排序规则
HarmonyOS鸿蒙Next中Waterflow组件排序规则 WaterFlow组件两列情况下,最后一项有时在左边有时在右边??
【背景知识】
瀑布流容器WaterFlow,由“行”和“列”分割的单元格所组成,通过容器自身的排列规则,将不同大小的“项目”自上而下,如瀑布般紧密布局。
RelativeContainer是一种采用相对布局的容器,支持容器内部的子元素设置相对位置关系,适用于处理界面复杂的场景,对多个子元素进行对齐和排列。子元素可以指定兄弟元素或父容器作为锚点,基于锚点进行相对位置布局。在使用锚点时,需注意子元素的相对位置关系,以避免出现错位或遮挡的情况。
【解决方案】
采用瀑布流排列时,为了保证布局均匀,规格设计上优先插入短的地方,不支持自己定义顺序。为了实现两列按自定义顺序排列,可以用RelativeContainer布局。示例代码为:
@Entry
@Component
struct WaterFlowComp {
@State data: string[] = ['1', '2', '3', '4', '5', '6']
@State colors: number[] = [0xFFC0CB, 0xDA70D6, 0x6B8E23, 0x6A5ACD, 0x00FFFF, 0x00FF7F]
getheigh(itemstr: string): number {
let heighnum = 40;
if (itemstr == '2' || itemstr == '3' || itemstr == '5') {
heighnum = 25;
}
return heighnum;
}
build() {
RelativeContainer() {
ForEach(this.data, (item: string) => {
if (item == '1') {
Text('N' + item)
.id('item' + item)
.alignRules({
top: { anchor: "__container__", align: VerticalAlign.Top },
left: { anchor: "__container__", align: HorizontalAlign.Start },
})
.height(this.getheigh(item))
.width('50%')
.backgroundColor(this.colors[Number(item)-1])
} else if (item == '2') {
Text('N' + item)
.id('item' + item)
.alignRules({
top: { anchor: "__container__", align: VerticalAlign.Top },
right: { anchor: "__container__", align: HorizontalAlign.End },
})
.height(this.getheigh(item))
.width('50%')
.backgroundColor(this.colors[Number(item)-1])
} else {
Text('N' + item)
.id('item' + item)
.alignRules({
top: { anchor: 'item' + (Number(item) - 2).toString(), align: VerticalAlign.Bottom },
left: { anchor: 'item' + (Number(item) - 2).toString(), align: HorizontalAlign.Start },
})
.height(this.getheigh(item))
.width('50%')
.backgroundColor(this.colors[Number(item)-1])
}
}, (item: string, index: number) => index.toString())
}
}
}
更多关于HarmonyOS鸿蒙Next中Waterflow组件排序规则的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
waterflow按顺序依次放置节点,放置时会放到当前最短的那一列上。
在HarmonyOS鸿蒙Next中,WaterFlow组件的排序规则主要基于数据源的顺序。默认情况下,WaterFlow会根据数据源列表中的顺序依次渲染每个数据项。开发者可以通过自定义布局管理器(如WaterFlowLayoutManager
)来调整排序规则,例如实现按特定条件(如时间、优先级等)排序。此外,还可以通过onItemSort
回调函数动态调整排序逻辑,以满足不同场景的需求。