现在有一段代码显示:
@Preview
@Component
export default struct Message {
item: string = '测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试'
isReceive:boolean = false
build() {
Column() {
Row() {
this.textMsgContent()
}
.margin({ top: 7.5, bottom: 7.5 })
.width('100%')
.direction(this.isReceive ? Direction.Ltr : Direction.Rtl)
.gesture(
LongPressGesture()
.onAction(() => {
promptAction.showToast({ message: '长按消息' })
})
)
}.width('100%')
.padding({ left: 15, right: 15 })
}
// 文字消息
@Builder
textMsgContent() {
Text(this.item)
.fontColor(this.isReceive ? $r('app.color.font_color_black_001A32') : Color.White)
.lineHeight(24)
.fontWeight(500)
.fontSize(15)
.backgroundColor(Color.RED)
.padding({ top: 10, bottom: 10, left: 15, right: 15 })
}
}
外部限制了width为'100%',padding左右都为15,内部Text组件采用根据内容宽度自适应的形式实现,为什么文本自动换行了,但是Text组件的宽度无法铺满外部padding左右都为15之后剩下的区域呢?总是在一侧会剩下一点间隙。
出现这种情况的原因是剩下的空间不足以显示一个汉字,而又没有设置Text的固定宽度,导致换行。
即使设置了最大宽度,在不满足显示空间时还是会自动换行,对于动态计算组件宽高,请参考以下文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/ts-universal-component-area-change-event-V5\#onareachange