1、概述
针对常见的开发场景,ArkUI开发框架提供了非常多的自适应布局能力,这些布局可以独立使用,也可多种布局叠加使用。本文针对ArkUI提供的显示优先级能力做简单讨论。
容器组件内的子组件,按照其预设的显示优先级,随容器组件尺寸变化显示或隐藏。相同显示优先级的子组件同时显示或隐藏。
2、显示优先级控制显隐
通过显示优先级可以实现组件的动态隐藏能力。
隐藏能力是指:容器组件内的子组件,按照其预设的显示优先级,随容器组件尺寸变化显示或隐藏,其中相同显示优先级的子组件同时显示或隐藏。
显隐控制是一种比较高级的布局方式,常用于分辨率变化较大,且不同分辨率下显示内容有所差异的场景。主要思想是通过增加或减少显示内容,来保持最佳的显示效果。
隐藏能力通过设置布局优先级(displayPriority属性)来控制显隐,当布局主轴方向剩余尺寸不足以满足全部元素时,按照布局优先级大小,从小到大依次隐藏,直到容器能够完整显示剩余元素。具有相同布局优先级的元素将同时显示或者隐藏。
3、displayPriority
displayPriority用于设置当前组件在布局容器中显示的优先级。接口定义如下:
// 设置当前组件在布局容器中显示的优先级。 value 默认值:
1displayPriority(value: number)
说明:
仅在Row/Column/Flex(单行)容器组件中生效。
小数点后的数字不作优先级区分,即区间为[x, x + 1)内的数字视为相同优先级。例如:1.0与1.9为同一优先级。
子组件的displayPriority均不大于1时,优先级没有区别。
当子组件的displayPriority大于1时,displayPriority数值越大,优先级越高。若父容器空间不足,隐藏低优先级子组件。若某一优先级的子组件被隐藏,则优先级更低的子组件也都被隐藏。
4、案例
父容器尺寸发生变化时,其子元素按照预设的优先级显示或隐藏。
代码如下:
@Entry
@Component
struct HiddenCapabilitySample {
@State rate: number = 0.45
// 底部滑块,可以通过拖拽滑块改变容器尺寸
@Builder slider() {
Slider({ value: this.rate * 100, min: 10, max: 45, style: SliderStyle.OutSet })
.blockColor(Color.White)
.width('60%')
.height(50)
.on=((value: number) => {
this.rate = value / 100
})
.positiion({ x: '20%', y: '80%' })
}
build() {
Column() {
Row({ space:24 }) {
Text('会话')
.width(48)
.height(48)
.textAlign(TextAlign.Center)
.displayPriority(1) // 布局优先级
Text('联系人')
.width(48)
.height(48)
.textAlign(TextAlign.Center)
.displayPriority(2) // 布局优先级
Text('短视频')
.width(48)
.height(48)
.textAlign(TextAlign.Center)
.displayPriority(3) // 布局优先级
Text('动态')
.width(48)
.height(48)
.textAlign(TextAlign.Center)
.displayPriority(2) // 布局优先级
Text('发现')
.width(48)
.height(48)
.textAlign(TextAlign.Center)
.displayPriority(1) // 布局优先级
}
.width(this.rate * 100 + '%')
.height(96)
.borderRadius(16)
.backgroundColor('#FFFFFF')
.justifyContent(FlexAlign.Center)
.alignItems(VerticalAlign.Center)
this.slider()
}
.width('100%')
.height('100%')
.backgroundColor('#F1F3F5')
.justifyContent(FlexAlign.Center)
.alignItems(HorizontalAlign.Center)
}
}