HarmonyOS鸿蒙Next中属性字符串的文档示例能不能写点基础用法示例

HarmonyOS鸿蒙Next中属性字符串的文档示例能不能写点基础用法示例 属性字符串的文档示例能不能写点基础用法,一上来就一大堆,对于不熟悉的人来说很难找到重点啊

文档链接

4 回复

开发者你好,可以看下属性字符串这个官方文档,以下为你提供一些使用示例:

1、使用AppStorage来传递属性字符串:

【背景知识】

  • 属性字符串:属性字符串StyledString/MutableStyledString(其中MutableStyledString继承自StyledString,下文统称为StyledString),可用于在字符或段落级别上设置文本样式。将StyledString应用到文本组件上,可以采用多种方式修改文本,包括调整字号、添加字体颜色、使文本具备可点击性,以及通过自定义方式绘制文本等。
  • AppStorage:AppStorage是与应用进程绑定的全局UI状态存储中心,由UI框架在应用启动时创建,将UI状态数据存储于运行内存,实现应用级全局状态共享。
// index.ets
import { LengthMetrics, router } from '@kit.ArkUI';

export class Param {
  mutableStyledString?: MutableStyledString
}

@Entry
@Component
struct Index {
  controller: TextController = new TextController();
  textStyleAttrs: TextStyle =
    new TextStyle({ fontWeight: FontWeight.Bolder, fontSize: LengthMetrics.vp(24), fontStyle: FontStyle.Italic })
  mutableStyledString: MutableStyledString = new MutableStyledString("运动35分钟 目标达成", [
    {
      start: 2,
      length: 2,
      styledKey: StyledStringKey.FONT,
      styledValue: this.textStyleAttrs
    },
    {
      start: 7,
      length: 4,
      styledKey: StyledStringKey.FONT,
      styledValue: new TextStyle({ fontColor: Color.Orange, fontSize: LengthMetrics.vp(12) })
    }
  ]);

  build() {
    Column() {
      Text(undefined, { controller: this.controller })
        .margin({ top: 10 }).onAppear(() => {
        this.controller.setStyledString(this.mutableStyledString)
      })

      Button("通过AppStorage传递属性字符串").onClick(() => {
        let param = new Param()
        param.mutableStyledString = this.mutableStyledString
        AppStorage.setOrCreate('mutableStyledString', param)

        router.pushUrl({
          url: "pages/Second",
        })
      })

    }
  }
}

// Second.ets
import { Param } from './Index';

@Component
@Entry
struct Second {
  controller: TextController = new TextController();

  build() {
    Column() {
      // 显示属性字符串
      Text(undefined, { controller: this.controller })
        .margin({ top: 10 }).onAppear(() => {

        let param = AppStorage.get<Param>('mutableStyledString')!
        this.controller.setStyledString(param.mutableStyledString)
      })
    }
    .width('100%')
    .height('100%')
  }
}

2、利用属性字符串实现文字长按变色:

【背景知识】

【解决方案】 可以利用属性字符串实现,实现思路如下:

  1. 参照官网示例-设置事件给Text绑定长按事件。
mutableStyledString: MutableStyledString = new MutableStyledString(this.message, [
  {
    start: 0,
    length: 5,
    styledKey: StyledStringKey.GESTURE,
    styledValue: this.clickGestureAttr
  },
  {
    start: 0,
    length: 5,
    styledKey: StyledStringKey.FONT,
    styledValue: this.fontStyleAttr1
  },
  {
    start: 6,
    length: 5,
    styledKey: StyledStringKey.FONT,
    styledValue: this.fontStyleAttr2
  }
]);
  1. 参照官网示例-属性字符串处理给已绑定的属性字符串实现长按替换效果。
clickGestureAttr: GestureStyle = new GestureStyle({
  onLongPress: () => {
    this.mutableStyledString.replaceStyle({
      start: 0,
      length: 5,
      styledKey: StyledStringKey.FONT,
      styledValue: new TextStyle({ fontColor: Color.Pink })
    });
    this.controller.setStyledString(this.mutableStyledString);
  }
})
  1. 完整的代码如下:
@Entry
@Component
struct Index {
  @State message: string = 'Hello World';
  fontStyleAttr1: TextStyle = new TextStyle({ fontColor: Color.Blue });
  fontStyleAttr2: TextStyle = new TextStyle({ fontColor: Color.Green });
  controller: TextController = new TextController();
  clickGestureAttr: GestureStyle = new GestureStyle({
    onLongPress: () => {
      this.mutableStyledString.replaceStyle({
        start: 0,
        length: 5,
        styledKey: StyledStringKey.FONT,
        styledValue: new TextStyle({ fontColor: Color.Pink })
      });
      this.controller.setStyledString(this.mutableStyledString);
    }
  })
  mutableStyledString: MutableStyledString = new MutableStyledString(this.message, [
    {
      start: 0,
      length: 5,
      styledKey: StyledStringKey.GESTURE,
      styledValue: this.clickGestureAttr
    },
    {
      start: 0,
      length: 5,
      styledKey: StyledStringKey.FONT,
      styledValue: this.fontStyleAttr1
    },
    {
      start: 6,
      length: 5,
      styledKey: StyledStringKey.FONT,
      styledValue: this.fontStyleAttr2
    }
  ]);

  async onPageShow() {
    this.controller.setStyledString(this.mutableStyledString);
  }

  build() {
    Column() {
      // 包含事件的属性字符串
      Text(undefined, { controller: this.controller })
        .fontSize(30)
        .copyOption(CopyOptions.InApp)
        .draggable(true)
        .clip(true)
    }
    .height('100%')
    .width('100%')
  }
}

更多关于HarmonyOS鸿蒙Next中属性字符串的文档示例能不能写点基础用法示例的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


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

  async onPageShow() {
    // 在生命周期onPageShow回调中绑定属性字符串
    this.controller1.setStyledString(this.styledString1);
  }

  build() {
    Column() {
      // 显示属性字符串
      Text(undefined, { controller: this.controller1 })
      Text(undefined, { controller: this.controller2 })
        .onAppear(() => {
          // 在组件onAppear回调中绑定属性字符串
          this.controller2.setStyledString(this.mutableStyledString1);
        })
    }
    .width('100%')
  }
}

参考地址

https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/arkts-styled-string#%E5%88%9B%E5%BB%BA%E5%B9%B6%E5%BA%94%E7%94%A8styledstring%E5%92%8Cmutablestyledstring

鸿蒙Next中属性字符串(AttributedString)的基础用法示例:

// 创建AttributedString
let attributedString = new AttributedString('Hello HarmonyOS');

// 添加文本样式
attributedString.addAttribute({
  attribute: FontAttribute.FontSize,
  value: 20,
  range: [0, 5]
});

// 添加颜色样式
attributedString.addAttribute({
  attribute: TextAttribute.TextColor,
  value: '#FF0000',
  range: [6, 12]
});

// 在Text组件中使用
Text(attributedString)
  .fontSize(16)

支持设置字体、颜色、下划线、背景色等属性,通过range参数控制应用范围。

属性字符串(StyledString)的基础用法其实很简单,主要用来在同一段文本中应用不同的样式(如颜色、字体、大小等)。以下是一个简洁的示例:

import { StyledString, StyleRange } from '@kit.ArkUI';

// 创建基础文本
let text = "HarmonyOS Next 开发";

// 定义样式范围:对"Next"应用红色
let styleRange: StyleRange = {
  start: 10, // "Next"起始位置
  length: 4,  // 长度为4个字符
  style: { color: '#FF0000' } // 红色样式
};

// 构建属性字符串
let styledString = new StyledString(text, [styleRange]);

// 在Text组件中使用
Text(styledString)
  .fontSize(20)

关键点:

  1. StyledString由原始文本和样式范围数组组成
  2. StyleRange指定起始位置、长度和要应用的样式
  3. 支持多种样式属性:color、fontSize、fontWeight等

这样就能快速实现文本部分样式差异化,比拆分多个Text组件更高效。

回到顶部