DEV Community

HarmonyOS
HarmonyOS

Posted on

How to Preserve Button Width with flexShrink(0) in HarmonyOS Wearable ArkUI Layouts

Read the original article:How to Preserve Button Width with flexShrink(0) in HarmonyOS Wearable ArkUI Layouts

Context

On HarmonyOS wearable screens, a row displays a long nickname followed by an “Add Friend” button. Desired behavior:

  • Long nicknames should truncate with ellipsis.
  • The button should keep its width and not shrink.
  • With short nicknames, the layout should remain undistorted.

Description

Inside a Column, a Flex(Row) is used. Due to Flex’s default shrink behavior, when horizontal space is tight the button shrinks, while the nickname may not truncate as expected, causing misalignment.

Solution

Make the button container non-shrinkable using .flexShrink(0), and apply maxLines(1) + textOverflow(Ellipsis) to the nickname for clean truncation.

@Entry
@Component
struct Index {

  build() {
    Column() {

      Blank().height('45%')

      Flex({ direction: FlexDirection.Row }) {
        Text('Long Nickname Here Here')
          .maxLines(1)
          .textOverflow({ overflow: TextOverflow.Ellipsis })

        Row() {
          Text('Add Friend')
            .textAlign(TextAlign.Center)
            .maxLines(1)
        }
        .flexShrink(0) // Prevent compression
        .justifyContent(FlexAlign.Center)
        .alignItems(VerticalAlign.Center)
        .backgroundColor('#E2EFFF')
        .padding({ left: 2, right: 2 })

      }
      .backgroundColor(Color.Red)

    }
    .height('100%')
    .width('100%')
  }
}
Enter fullscreen mode Exit fullscreen mode

Key Takeaways

  • Flex children shrink by default; protect critical UI with .flexShrink(0).
  • maxLines(1) + textOverflow(Ellipsis) reliably truncates long text.
  • This pattern preserves button stability and readability on small wearable screens.

Without flexShrink(0) Command:

s1.png

With flexShrink(0) Command:

s2.png

Additional Resources

https://developer.huawei.com/consumer/en/doc/harmonyos-references/ts-universal-attributes-flex-layout#flexshrink

Written by Bunyamin Eymen Alagoz

Top comments (0)