目录

如何实现基于StyledString的气泡动态适配

问题现象

如何根据StyledString文本高度动态调整气泡的高度?

效果预览

可以看到气泡大小会跟随StyledString而变化。

背景知识

解决方案

气泡高度的动态调整可通过Column自适应Text内容实现,StyledString提供样式化文本内容,其高度由Text组件渲染后自动传递给Column。

@Builder
function bubbleBackgroundOne() {
  Image($r('app.media.backgroundcolorgray')) // 此处'backgroundcolorgray'仅作示例,请开发者自行替换。
    .objectFit(ImageFit.Fill)
    .width('100%')
    .height('100%');
}

@Entry
@Component
struct StyledStringDemo {
  styledString1: StyledString = new StyledString('运动45分钟');
  mutableStyledString1: MutableStyledString = new MutableStyledString('运动35分钟');
  controller1: TextController = new TextController();
  controller2: TextController = new TextController();

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

  build() {
    Row() {
      Column() {
        // 显示属性字符串
        Text(undefined, { controller: this.controller1 });
        Text(undefined, { controller: this.controller2 });
        Text('测试')
          .onClick(async () => {
            this.styledString1 = new StyledString('运动45分钟XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');
            this.controller1.setStyledString(this.styledString1);
          })
      }
      .background(bubbleBackgroundOne)
      .padding(10)
      .borderRadius(5)
      .width('100%');
    }
    .height('100%')
    .width('100%')
    .padding(10);
  }
}