HarmonyOS NEXT鸿蒙开发ArkUI:右侧固定宽度、左侧自适应宽度(弹性布局)

介绍

如下图,右侧红框是固定宽度,左侧自适应宽度(文字自动换行)

实现

官方指南

官方API

外部

外部是 Row 布局

内部左侧

是 Column 布局,必须加下面弹性布局:

.flexGrow(1)      // 关键:占满剩余空间
.flexShrink(1)    // 关键:当父容器空间不足时,子元素的压缩比例,防止组件宽度过,挤出去

里面的 Text 组件必须加宽度,如:100%,否则不会换行

内部右侧

是 Row 布局,必须加固定宽度

代码

Row() {
  Column({ space: 8 }) {
    Text(item.deviceName+"("+item.deviceCode+")")
      .fontSize(16)
      .fontColor('#333')
      .align(Alignment.Start)
      .width('100%')         

    Text("预警:"+item.msg)
      .fontSize(16)
      .fontColor('#333')
      .align(Alignment.Start)
      .width('100%')         

    Text(item.createTime)
      .fontSize(16)
      .fontColor('#333')
      .align(Alignment.Start)
      .width('100%')         
  }
  .align(Alignment.Start)
  .flexGrow(1)      // 关键:占满剩余空间
  .flexShrink(1)    // 关键:当父容器空间不足时,子元素的压缩比例,防止组件宽度过,挤出去

  Row() {
    // 彩色指示器
    Circle({ width: 40, height: 40 })
      .fill(this.getColor(item.mark))
      .opacity(0.2)

    Circle({ width: 20, height: 20 })
      .fill(this.getColor(item.mark))
      .margin({ left: -30 })
  }
  .width(50)
}
.width('100%')
// .height(100)
.backgroundColor('#FFFFFF')
.borderRadius(16)
.padding({
  left:8,
  right:8,
  bottom:8,
})
.shadow({
  radius: 8,
  color: '#1a000000',
  offsetX: 0,
  offsetY: 2
})

原文出处:/show_1GW34nUgJZxw.html