DEV Community

HarmonyOS
HarmonyOS

Posted on

How to Achieve Dynamic Bubble Adaptation Based on StyledString

Read the original article:How to Achieve Dynamic Bubble Adaptation Based on StyledString

Requirement Description

How to dynamically adjust the height of a bubble based on the height of StyledString text?

Background Knowledge

The StyledString object supports flexible text styling and can be bound to the Text component via the setStyledString method of TextController, or associated with the RichEditor component through the controller methods of RichEditor.
The objectFit method is used to set the fill effect of images.

Implementation Steps

The dynamic adjustment of bubble height can be achieved by making the Column adapt to the Text content.

StyledString provides styled text content, and its height is automatically passed to the Column after being rendered by the Text component.

Code Snippet

@Builder
function bubbleBackground() {
  Image($r('app.media.backgroundcolorgray')) // Here, 'backgroundcolorgray' is used as an example; developers are advised to replace it accordingly.
    .objectFit(ImageFit.Fill)
    .width('100%')
    .height('100%')
}

@Entry
@Component
struct Index1 {
  styledString1: StyledString = new StyledString('Exercise for 45 minutes')
  mutableStyledString1: MutableStyledString = new MutableStyledString('Exercise for 35 minutes')
  controller1: TextController = new TextController()
  controller2: TextController = new TextController()

  async onPageShow() {
    this.controller1.setStyledString(this.styledString1)
    this.controller2.setStyledString(this.mutableStyledString1)
  }

  build() {
    Row() {
      Column() {
        // Display Attribute String
        Text(undefined, { controller: this.controller1 })
        Text(undefined, { controller: this.controller2 })
        Text('Test')
      }
      .background(bubbleBackground)
      .padding(10)
      .borderRadius(5)
      .width('100%')
    }
    .height('100%')
    .width('100%')
    .padding(10)
  }
}
Enter fullscreen mode Exit fullscreen mode

kbs--340acf23c9cd4e50ac8783493ea4ac8f-14ca2.png kbs--6c2ddd69d25f4bc8815161a1325c8001-21e69.png

Limitations or Considerations

This example supports API Version 19 Release and above.
This example supports HarmonyOS 5.1.1 Release SDK and above.
This example requires DevEco Studio 5.1.1 Release and above for compilation and execution.

Written by Dogan Evci

Top comments (0)