【每日学点鸿蒙知识】ASON工具、自定义tabbar、musl、Text异常截断等

1、如何使用ASON工具实现Sendable类型和JSON数据的转换?

ASON支持开发者解析JSON字符串,并生成共享数据进行跨并发域传输,同时ASON也支持将共享数据转换成JSON字符串。

复制代码
import { ArkTSUtils, collections, lang } from '@kit.ArkTS';

// JSON解析为Sendable数据
type ISendable = lang.ISendable;
let jsonText = '{"name": "John", "age": 30, "city": "ChongQing"}';
let obj = ArkTSUtils.ASON.parse(jsonText) as ISendable;

// Sendable数据序列化为JSON
let arr = new collections.Array(1, 2, 3);
let str = ArkTSUtils.ASON.stringify(arr);

参考地址:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-arkts-utils-V5#arktsutilsason

2、如何在Tabs中的tabBar,添加其他组件?

目前有很多tabs组件最右边的tabbar会有筛选更多的图标,但是目前tabs系统组件无法在tabbar中添加其他组件,可以使用自定义来实现Tabs中的tabBar,添加其他组件。

复制代码
import componentUtils from '@ohos.arkui.componentUtils';

@Entry
@Component
struct TabsExample22 {
  @State tabArray: Array<number> = [0, 1, 2]
  private controller: TabsController = new TabsController()
  @State currentIndex: number = 0
  @State animationDuration: number = 300
  @State indicatorLeftMargin: number = 0
  @State indicatorWidth: number = 0
  private tabsWidth: number = 0

  // 单独的页签
  @Builder
  Tab(tabName: string, tabItem: number, tabIndex: number) {
    Row({ space: 20 }) {
      Text(tabName).fontSize(18)
        .fontColor(tabItem === this.currentIndex ? Color.Red : Color.Black)
        .id(tabIndex.toString())
        .onAreaChange((oldValue: Area, newValue: Area) => {
          if (this.currentIndex === tabIndex && (this.indicatorLeftMargin === 0 || this.indicatorWidth === 0)) {
            if (newValue.position.x != undefined) {
              let positionX = Number.parseFloat(newValue.position.x.toString())
              this.indicatorLeftMargin = Number.isNaN(positionX) ? 0 : positionX
            }
            let width = Number.parseFloat(newValue.width.toString())
            this.indicatorWidth = Number.isNaN(width) ? 0 : width
          }
        })
    }
    .justifyContent(FlexAlign.Center)
    .constraintSize({ minWidth: 35 })
    .width(80)
    .height(35)
    .borderRadius({ topLeft: 10, topRight: 10 })
    .onClick(() => {
      this.controller.changeIndex(tabIndex)
      this.currentIndex = tabIndex
    })

  }

  build() {
    Column() {
      // 页签
      Stack({ alignContent: Alignment.TopStart }) {
        Scroll() {
          Row() {
            ForEach(this.tabArray, (item: number, index: number) => {
              this.Tab("页签 " + item, item, index)
            })


            Text('+')
              .width(36)
              .height(50)
              .fontSize(28)
              .borderRadius(5)
              .margin({ left: 88 })
              .padding({ left: 5, bottom: 2 })
          }
          .justifyContent(FlexAlign.Start)
        }
        .align(Alignment.Start)
        .scrollable(ScrollDirection.Horizontal)
        .scrollBar(BarState.Off)
        .width('100%')

        Column()
          .width(this.indicatorWidth)
          .height(2)
          .backgroundColor(Color.Red)
          .borderRadius(2)
          .margin({ left: this.indicatorLeftMargin, top: 38 })
      }
      .width('100%')

      .width('100%')

      //tabs
      Tabs({ barPosition: BarPosition.Start, controller: this.controller }) {
        ForEach(this.tabArray, (item: number, index: number) => {
          TabContent() {
            Text('我是页面 ' + item + " 的内容")
              .height(300)
              .width('100%')
              .fontSize(30)
          }
          .backgroundColor(Color.Pink)
        })
      }
      .onAreaChange((oldValue: Area, newValue: Area) => {
        let width = Number.parseFloat(newValue.width.toString())
        this.tabsWidth = Number.isNaN(width) ? 0 : width
      })
      .barWidth('100%')
      .barHeight(0)
      .width('100%')
      .height('100%')
      .backgroundColor('#F1F3F5')
      .animationDuration(this.animationDuration)
      .onChange((index: number) => {
        this.currentIndex = index // 监听索引index的变化,实现页签内容的切换。
      })
      .onAnimationStart((index: number, targetIndex: number, event: TabsAnimationEvent) => {
        // 切换动画开始时触发该回调。下划线跟着页面一起滑动,同时宽度渐变。
        this.currentIndex = targetIndex
        let targetIndexInfo = this.getTextInfo(targetIndex)
        this.startAnimateTo(this.animationDuration, targetIndexInfo.left, targetIndexInfo.width)
      })
      .onAnimationEnd((index: number, event: TabsAnimationEvent) => {
        // 切换动画结束时触发该回调。下划线动画停止。
        let currentIndicatorInfo = this.getCurrentIndicatorInfo(index, event)
        this.startAnimateTo(0, currentIndicatorInfo.left, currentIndicatorInfo.width)
      })
      .onGestureSwipe((index: number, event: TabsAnimationEvent) => {
        // 在页面跟手滑动过程中,逐帧触发该回调。
        let currentIndicatorInfo = this.getCurrentIndicatorInfo(index, event)
        this.currentIndex = currentIndicatorInfo.index
        this.indicatorLeftMargin = currentIndicatorInfo.left
        this.indicatorWidth = currentIndicatorInfo.width
      })
    }
    .height('100%')
  }

  // 获取组件大小、位置、平移缩放旋转及仿射矩阵属性信息。
  private getTextInfo(index: number): Record<string, number> {
    let modePosition: componentUtils.ComponentInfo = componentUtils.getRectangleById(index.toString());
    return { 'left': px2vp(modePosition.windowOffset.x), 'width': px2vp(modePosition.size.width) }
  }

  private getCurrentIndicatorInfo(index: number, event: TabsAnimationEvent): Record<string, number> {
    let nextIndex = index
    if (index > 0 && event.currentOffset > 0) {
      nextIndex--
    } else if (index < 3 && event.currentOffset < 0) {
      nextIndex++
    }
    let indexInfo = this.getTextInfo(index)
    let nextIndexInfo = this.getTextInfo(nextIndex)
    let swipeRatio = Math.abs(event.currentOffset / this.tabsWidth)
    let currentIndex = swipeRatio > 0.5 ? nextIndex : index // 页面滑动超过一半,tabBar切换到下一页。
    let currentLeft = indexInfo.left + (nextIndexInfo.left - indexInfo.left) * swipeRatio
    let currentWidth = indexInfo.width + (nextIndexInfo.width - indexInfo.width) * swipeRatio
    return { 'index': currentIndex, 'left': currentLeft, 'width': currentWidth }
  }

  private startAnimateTo(duration: number, leftMargin: number, width: number) {
    animateTo({
      duration: duration, // 动画时长
      curve: Curve.Linear, // 动画曲线
      iterations: 1, // 播放次数
      playMode: PlayMode.Normal, // 动画模式
      onFinish: () => {
        console.info('play end')
      }
    }, () => {
      this.indicatorLeftMargin = leftMargin
      this.indicatorWidth = width
    })
  }
}

3、C/musl库支持情况?

HarmonyOS采用musl作为C标准库,musl库是一个轻量,快速,简单,免费的开源libc库,详细介绍参考musl官方参考手册。musl与glibc的差异点请参考musl与glibc功能对比

musl版本号

  • 从HarmonyOS4.0开始,版本升级到1.2.3
  • 从HarmonyOS5.0开始,版本升级到1.2.5

支持的能力

提供兼容C99,C11,POSIX标准的头文件,以及库函数接口,但不是完全兼容;

4、如何解决Text组件文本为内容中文、数字、英文混合时显示省略号截断异常?

在使用text文本组件时,若text组件中文本内容为中文、数字、英文混合时,TextOverFlow设置文本超长时显示省略号出现截断异常。

Text组件设置wordBreak(WordBreak.BREAK_ALL)属性时,对于Non-CJK的文本,可在任意2个字符间断行即可正常截断。

复制代码
@Entry
@Component
struct Index {
  @State text: string = '2年·VIP会员 3个月期·8GB·230mm·花漾粉'

  build() {
    Column() {
      Text(this.text)
        .width(200)//设置最大行数
        .maxLines(1)//文本超长显示
        .textOverflow({ overflow: TextOverflow.Ellipsis })//文本超长显示省略号
        .ellipsisMode(EllipsisMode.END)//设置断行规则WordBreak.BREAK_ALL后
        .wordBreak(WordBreak.BREAK_ALL)
        .textAlign(TextAlign.JUSTIFY)
        .backgroundColor(Color.Green)
        .fontSize(16)
        .fontColor(Color.Red)
    }
  }
}

5、HarmonyOS编解码接口标准?

encodeURIComponent是TS自带的能力,URI编码是基于RFC 3986标准的。

相关推荐
键盘鼓手苏苏7 小时前
Flutter 三方库 p2plib 的鸿蒙化适配指南 - 实现高性能的端到端(P2P)加密通讯、支持分布式节点发现与去中心化数据流传输实战
flutter·harmonyos·鸿蒙·openharmony
加农炮手Jinx7 小时前
Flutter for OpenHarmony:postgrest 直接访问 PostgreSQL 数据库的 RESTful 客户端(Supabase 核心驱动) 深度解析与鸿蒙适配指南
数据库·flutter·华为·postgresql·restful·harmonyos·鸿蒙
加农炮手Jinx7 小时前
Flutter 组件 heart 适配鸿蒙 HarmonyOS 实战:分布式心跳监控,构建全场景保活检测与链路哨兵架构
flutter·harmonyos·鸿蒙·openharmony
钛态8 小时前
Flutter 三方库 http_mock_adapter — 赋能鸿蒙应用开发的高效率网络接口 Mock 与自动化测试注入引擎(适配鸿蒙 HarmonyOS Next ohos)
android·网络协议·flutter·http·华为·中间件·harmonyos
王码码20358 小时前
Flutter for OpenHarmony:Flutter 三方库 algoliasearch 毫秒级云端搜索体验(云原生搜索引擎)
android·前端·git·flutter·搜索引擎·云原生·harmonyos
王码码20358 小时前
Flutter 三方库 dns_client 的鸿蒙化适配指南 - 告别 DNS 劫持、探索 DNS-over-HTTPS (DoH) 技术、构建安全的鸿蒙网络请求环境
flutter·harmonyos·鸿蒙·openharmony·dns_client
键盘鼓手苏苏8 小时前
Flutter 组件 highlighter 适配鸿蒙 HarmonyOS 实战:高性能语法高亮,构建大规模代码分析与文本染色架构
flutter·harmonyos·鸿蒙·openharmony
国医中兴8 小时前
Flutter 三方库 langchain_google 的鸿蒙化适配指南 - 链接 Gemini 智慧中枢、LangChain AI 实战、鸿蒙级智能应用专家
flutter·langchain·harmonyos
左手厨刀右手茼蒿8 小时前
Flutter for OpenHarmony: Flutter 三方库 shamsi_date 助力鸿蒙应用精准适配波斯历法(中东出海必备)
android·flutter·ui·华为·自动化·harmonyos
雷帝木木8 小时前
Flutter 三方库 http_client_interceptor 的鸿蒙化适配指南 - 实现原生 HttpClient 的全量请求拦截、支持端侧动态 Headers 注入与网络流量审计实战
flutter·harmonyos·鸿蒙·openharmony·http_client_interceptor