HarmonyOS鸿蒙学习笔记(10)Flex中Text组件文字居中问题

Flex组件中使用Text组件的时候,发现无法让Text的文字剧中展示,代码如下:

@Entry
@Component
struct Index {
    
    
  build() {
    
    
    Column() {
    
    
      Flex() {
    
    
        //TextAlign.Center,TextAlign:	设置多行文本的文本对齐方式。
        Text('1').textAlign(TextAlign.Center).width('20%').height(50).backgroundColor(0xF5DEB3)
        Text('2').textAlign(TextAlign.Center).width('20%').height(50).backgroundColor(0xD2B48C)
        Text('3').textAlign(TextAlign.Center).width('20%').height(50).backgroundColor(0xF5DEB3)
        Text('4').textAlign(TextAlign.Center).width('20%').height(50).backgroundColor(0xD2B48C)
      }
      .height(70)
      .width('100%')
      .backgroundColor(0xAFEEEE)
    }.justifyContent(FlexAlign.Center)
    .alignItems(HorizontalAlign.Center)
    .height('100%')
    .width('100%')
  }
}

运行效果如下,可以看出四个Text的文字只是贴着上部居中,没有在中心位置展示:
在这里插入图片描述
解决方式为为Flex配置alignItems:ItemAlign即可,试验发现只要alignItems:ItemAlign不是ItemAlign.Stretch就可以实现居中:

Flex({
    
     alignItems:ItemAlign.Start}) {
    
    }

最终效果:
在这里插入图片描述

但是总感觉这种解决方式不正规,后面再仔细研究下。
参考资料:
ItemAlign官方说明
30 分钟学会 Flex 布局

猜你喜欢

转载自blog.csdn.net/chunqiuwei/article/details/126951158