场景一:如何实现Flex布局中只显示固定行数的Button,超出固定行数的Button按钮不显示?
场景二:Text组件和Image组件使用Row包裹,Text组件内容过长会导致超出组件本身大小,如何规避?
场景三:在Row里,处于中间位置的Text组件在只显示一行的前提下如何宽度自适应?
import { LengthMetrics } from '@kit.ArkUI';
@Entry
@Component
struct Solution1 {
@State allData: string[] =
['1', '22', '333', '44444', '55', '666', '7777', '8888', '99', '222', '5555', '8888', '44444444',
'666666', '7777', '44444', '55', '666', '7777', '8888'];
@Builder
TextItem(message: string) {
Button(message)
.fontSize(16)
.backgroundColor('#c4c2cc')
.height(45);
}
build() {
Column() {
Flex() {
Flex({ wrap: FlexWrap.Wrap, space: { main: LengthMetrics.vp(10), cross: LengthMetrics.vp(10) } }) {
ForEach(
this.allData,
(item: string) => {
this.TextItem(item);
}
);
}
.margin(10) // 与外层Flex间隔为10
.constraintSize({ maxHeight: 45 * 4 + 10 * 3 }) // 设置内层Flex最大高度为4个Button的高度+Button之间的间隔
.clip(true) // 超出部分不显示
.width('100%');
}.border({ width: 1 }).width('80%'); // 外层Flex不设置高度,自适应内层Flex高度
}.width('100%').height('100%').justifyContent(FlexAlign.Center);
}
} 实现效果如下:

具体实现可参考如下示例:
import { display } from '@kit.ArkUI';
@Entry
@Component
struct Solution2 {
// 屏幕宽度-单位为px
screenWidthPx: number = 0;
// 屏幕宽度-单位为vp
@State screenWidth: number = 0;
aboutToAppear(): void {
// 获取显示设备的屏幕宽度,单位为px
this.screenWidthPx = display.getDefaultDisplaySync().width;
// 将px转换为vp
this.screenWidth = this.getUIContext().px2vp(this.screenWidthPx);
}
build() {
Column() {
Row({ space: 10 }) {
Image($r('app.media.startIcon')) // 图片资源需自行替换
.width(40);
Text('测试一段长文字测试一段长文字测试一段长文字测试一段长文字测试一段长文字测试一段长文字测试一段长文字测试一段长文字测试一段长文字')
.backgroundColor('#F1F3F5')
.constraintSize({ maxWidth: this.screenWidth - 40 - 20 - 20 - 10 }); // 约束宽度,屏幕宽-图片宽-左右margin-间隔
}
.width('100%')
.margin(20)
.justifyContent(FlexAlign.Center);
}
.height('100%')
.width('100%');
}
} 实现效果如下:

@Entry
@Component
struct Solution {
build() {
Row() {
Image('')
.backgroundColor(Color.Orange)
.width(16)
.height(16)
.borderRadius(8);
Text('这是用户名这是用户名这是用户名这是用户名这是用户名这是用户名这是用户名这是用户名')
.fontSize(14)
.fontColor(Color.Black)
.margin({ left: 3 })
.textOverflow({ overflow: TextOverflow.Ellipsis })
.maxLines(1)
.constraintSize({ maxWidth: 260 });
Text('+ 关注')
.fontSize(10)
.fontColor(Color.White)
.backgroundColor(Color.Orange)
.padding({ left: 5, right: 5, })
.height(15)
.margin({ left: 5 })
.borderRadius(2);
}
.justifyContent(FlexAlign.Center)
.alignItems(VerticalAlign.Center)
.width('100%')
.height(20)
.margin({ top: 20 });
}
} 实现效果如下:
