通过子组件之间的相对关系或子组件与父组件(__container__)的相对关系来布局,需结合 alignRules 方法和 id 属性实现。
基础用法步骤
对齐规则的属性与取值
alignRules 支持以下属性(用于定义组件在垂直方向和水平方向的对齐逻辑):
| 方向 | 属性名 | 对齐方式取值(VerticalAlign/HorizontalAlign) | 说明 |
|---|---|---|---|
| 垂直方向 | top | Top/Center/Bottom | 组件的顶部、垂直中心、底部与锚点的对应位置对齐 |
| 垂直方向 | center | Top/Center/Bottom | 同上(center 是垂直方向的 “中心对齐” 属性,命名容易混淆,需注意) |
| 水平方向 | left | Start/Center/End | 组件的左边缘、水平中心、右边缘与锚点的对应位置对齐(Start 对应左,End 对应右) |
| 水平方向 | middle | Start/Center/End |
同上(middle 是水平方向的 “中心对齐” 属性) |
使用
|
1 2 3 4 5 6 7 8 9 10 11 |
//组件居中显示
RelativeContainer() { Text("居中组件") .width(100) .height(100) .alignRules({ center: {anchor: "__container__", align: VerticalAlign.Center}, // 垂直居中 middle: {anchor: "__container__", align: HorizontalAlign.Center} // 水平居中 }) } |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
//组件相对排列
RelativeContainer() { Text("组件A") .width(100) .height(100) .backgroundColor(Color.Red) .id("A") Text("组件B") .width(100) .height(100) .backgroundColor(Color.Blue) .alignRules({ top: {anchor: "A", align: VerticalAlign.Bottom}, // 组件B的顶部对齐组件A的底部 left: {anchor: "A", align: HorizontalAlign.End} // 组件B的左边缘对齐组件A的右边缘 }) } |
注意事项
通过文本显示计时信息并控制其计时器状态的组件。
| 名称 | 类型 | 只读 | 可选 | 说明 |
|---|---|---|---|---|
| isCountDown | boolean | 否 | 是 |
倒计时开关。值为true时,计时器开启倒计时,例如从30秒 ~ 0秒。值为false时,计时器开始计时,例如从0秒 ~ 30秒。 默认值:false |
| count | number | 否 | 是 |
计时器时间(isCountDown为true时生效),单位为毫秒。最长不超过86400000毫秒(24小时)。 0<count<86400000时,count值为计时器初始值。否则,使用默认值为计时器初始值。 默认值:60000 |
| controller |
TextTimerController |
否 | 是 | TextTimer控制器。 |
format属性
设置自定义格式,需要至少包含一个HH、mm、ss、SS
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
| value | string | 是 |
自定义格式。 默认值:'HH:mm:ss.SS' |
ontimer事件
onTimer(event: (utc: number, elapsedTime: number) => void)
时间文本发生变化时触发该事件。锁屏状态和应用后台状态下不会触发该事件。
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
| utc | number | 是 | Linux时间戳,即自1970年1月1日起经过的时间,单位为设置格式的最小单位。 |
| elapsedTime | number | 是 | 计时器经过的时间,单位为设置格式的最小单位。 |
TextTimerController
TextTimer组件的控制器,用于控制文本计时器。一个TextTimer组件仅支持绑定一个控制器,组件创建完成后相关指令才能被调用。
导入对象
|
1 |
textTimerController: TextTimerController = new TextTimerController(); |
使用
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
@Entry @Component struct time { textTimerController: TextTimerController = new TextTimerController();
onPageShow(): void { this.textTimerController.start()
}
@State countdown: boolean = true
build() { Column() { TextTimer({ count: 5000, controller: this.textTimerController, isCountDown: this.countdown }) .format('ss') .fontSize(25) .onTimer( (utc: number, passtime) => { if (passtime == 5) { this.getUIContext().getRouter().pushUrl({ url: "pages/RelativeContainer" }) } } ) }.width('100%') } } |