鸿蒙Next如何自定义标签页

server/2025/3/1 0:58:59/

前言

项目需求是展示标签,标签的个数不定,一行展示不行就自行换行。但是,使用鸿蒙原生的 Grid 后发现特别的难看。然后就想着自定义控件。找了官方文档,发现2个重要的实现方法,但是,官方的demo中讲的很少,需要自己去看去思考。

效果图如下:
在这里插入图片描述
注意点:

  1. 需要计算整体布局的宽高,这和 Android 差不多。
  2. 注意 margin 的计算

具体的代码如下:

/*** 自定义标签页面*/
@Component struct CustomTagView {screenWidth: number = 0aboutToAppear(): void {let dis = display.getDefaultDisplaySync();let width = dis.widthlet height = dis.height// width 是单位是 px, 转换为 vp ,因为 onMeasureSize 和 onPlaceChildren 得到的 width margin 以及 padding 都是 vplet w = px2vp(width)let h = px2vp(height)this.screenWidth = wconsole.log("TagView aboutToAppear width = " + width + " , height = " + height + ", w = " + w + ", h = " + h)}@Builder childBuilder() {}@BuilderParam buildTagView: () => void = this.childBuilderresult: SizeResult = {width: 0,height: 0}// 第一步:计算各子组件的实际大小以及设置布局本身的大小onMeasureSize(selfLayoutInfo: GeometryInfo, children: Array<Measurable>, constraint: ConstraintSizeOptions) {let parentWidth = selfLayoutInfo.widthlet parentHeight = selfLayoutInfo.heightconsole.log("TagView onMeasureSize parentWidth = " + parentWidth + " , parentHeight = " + parentHeight)let startPosX = 0let columNumber = 1let childHeight = 0children.forEach((child) => {// 得到子控件的实际大小let result: MeasureResult = child.measure({minHeight: constraint.minHeight,minWidth: constraint.minWidth,maxWidth: constraint.maxWidth,maxHeight: constraint.maxHeight})let padding = child.getPadding()let border = child.getBorderWidth()console.log("TagView onMeasureSize = child width = " + result.width + "  ,  height = " + result.height+ " , padding = [" + padding.start + ", " + padding.end + ", " + padding.top + ", " + padding.bottom +"], border = ["+ border.start + ", " + border.end + ", " + border.top + ", " + border.bottom + "]")/// 计算 布局所需的高度, 宽度默认为屏幕的宽度childHeight = result.height + child.getMargin().topstartPosX += result.width + child.getMargin().startif (startPosX > parentWidth) {columNumber++startPosX = result.width + child.getMargin().start}})// 父布局的宽和高,即承载 child 布局的宽和高,这里指的就是 TagView 的宽和高this.result.width = this.screenWidth;this.result.height = childHeight * columNumber + 10 // 加10是为了底部多点空间return this.result;}// 第二步:放置各子组件的位置onPlaceChildren(selfLayoutInfo: GeometryInfo, children: Array<Layoutable>, constraint: ConstraintSizeOptions) {let startPosX = 0let startPosY = 0let posY = 0let parentWidth = selfLayoutInfo.widthconsole.log("TagView onPlaceChildren parentWidth = " + selfLayoutInfo.width + " , parentHeight = " + selfLayoutInfo.height)children.forEach((child) => {startPosX += child.getMargin().start// 如果一行的控件的长度大于屏幕宽度则换行if (startPosX + child.measureResult.width > parentWidth) {startPosY += child.measureResult.height + child.getMargin().topstartPosX = child.getMargin().start}posY = startPosYconsole.log("TagView child width = " + child.measureResult.width + "  ,  height = " + child.measureResult.height +" , margin left = " + child.getMargin().start)child.layout({ x: startPosX, y: posY })startPosX += child.measureResult.width})}build() {this.buildTagView()}
}
调用的方法也很简单,下面是个调用的demo
@Entry
@Component
struct TestPage {@State name: string = 'hello'// @Provide 参数 key 必须是 string@Provide('provideName') pName: string = "哈哈"@Provide('count') count: number = 4textWidth: number = 0aboutToAppear(): void {let width = MeasureText.measureText({ textContent: '返厂无忧券1', fontSize: '13vp' });let w = px2vp(width)console.log("TestPage aboutToAppear >>>> width = " + width + " , w = " + w)// 如果有换行,那么长度等于最长的一行let textSize = MeasureText.measureTextSize({ textContent: '返厂无忧券1\n返厂无忧券1234', fontSize: '13vp' })let w2 = textSize.widthlet h2 = textSize.heightthis.textWidth = px2vp(w2 as number)console.log("TestPage aboutToAppear >>>> w2 = " + w2 + " , h2 = " + h2)}// @Build 参数按值传递,状态变量改变不会引起 @Build 方法内的 UI 刷新// 但是,Text(" ----- " + this.name) 中的 UI 会刷新@BuildernameView(name: string) {Text(name)}//  @Build 参数按引用传递的话,状态变量(@State name) 改变,@Build 方法内的 UI 会刷新@BuildernameView2(tmp: Tmp) {Text('V2 : name = ' + tmp.params)}// 通过builder的方式传递多个组件,作为自定义组件的一级子组件(即不包含容器组件,如Column)@BuilderTagViewChildren() {ForEach(['你好,哪吒2', '大圣归来啊', '我是名字超长的但是很厉害', 'hello world', '你真的好厉害啊哈哈', '没空看', '非凡','再来一个很长的名字啊', 'OK'],(data: string, index: number) => { // 暂不支持lazyForEach的写法Text(data).fontSize(13).fontColor(Color.Red).margin({ left: 3, top: 4 })// .width(100)// .height(100).borderWidth(1).border({ radius: 4 }).padding(5).textAlign(TextAlign.Center)// .offset({ x: 10, y: 20 })})}build() {Column() {Column() {CustomTagView({ buildTagView: this.TagViewChildren })}.backgroundColor(Color.Pink).margin({ top: 2 })}.width('100%').height('100%').alignItems(HorizontalAlign.Start)}
}

好了,具体的可以参考下 demo 啦,有疑问的可以一起交流。


http://www.ppmy.cn/server/171428.html

相关文章

C# 中 Array、ArrayList 和 List 的比较

C# 中 Array、ArrayList 和 List 的比较 在 C# 中&#xff0c;Array、ArrayList 和 List<T> 都用于存储和管理数据集合&#xff0c;但它们在类型安全性、性能、灵活性和使用场景上存在显著差异。以下是对这三种集合的详细比较&#xff1a; 1. 概述 特性ArrayArrayList…

【Python爬虫(95)】Python爬虫进阶:构建大型垂直领域爬虫系统

【Python爬虫】专栏简介:本专栏是 Python 爬虫领域的集大成之作,共 100 章节。从 Python 基础语法、爬虫入门知识讲起,深入探讨反爬虫、多线程、分布式等进阶技术。以大量实例为支撑,覆盖网页、图片、音频等各类数据爬取,还涉及数据处理与分析。无论是新手小白还是进阶开发…

Unity Shader 学习14:模版测试 与 深度测试

目录 一、模版检测 1. 概念 ① 比较 Comp ② 更新 Pass 2. 示例分析 - 3D卡牌 二、深度检测 1. 概念 ① 比较&#xff1a;深度测试 Z-Test ② 更新&#xff1a;深度写入 Z-Write 2. 示例分析 一、模版检测 核心&#xff1a;当前模版缓冲区中的值 [stencilBufferValu…

2步本地安装部署国产之光大模型DeepSeek,附Mac安装教程和安装包!

轻松两步本地运行国产大模型DeepSeek&#xff0c;附Windows与Mac教程及安装包&#xff01; 在短短一夜之间&#xff0c;DeepSeek-R1&#xff0c;中国的AI大模型&#xff0c;以惊人的速度崛起&#xff0c;引发了全球科技界的广泛关注。英伟达AI科学家Jim Fan也对此表示惊讶&…

子组件如何通过v-model实现数据的双向绑定

在 Vue 中&#xff0c;v-model 是一种语法糖&#xff0c;用于在表单元素或者组件上实现双向数据绑定。 下面分别介绍在 Vue 2 和 Vue 3 里子组件使用 v-model 实现数据双向绑定的具体方式。 Vue 2 中使用 v-model 实现双向绑定 在 Vue 2 里&#xff0c;v-model 本质上是 :va…

服务异步通讯与RabbitMQ

服务异步通讯 文章目录 服务异步通讯MQRabbitMQ1、安装&#xff08;部署&#xff09;2、结构3、消息模型4、SpringAMQP4.1、基本消息队列4.2、工作消息队列4.3、发布订阅模型4.3.1、FanoutExchange&#xff08;广播类型的交换机&#xff09;4.3.2、DirectExchange&#xff08;路…

【Redis】在Java中以及Spring环境下操作Redis

Java环境下&#xff1a; 1.创建maven 项目 2.导入依赖 <!-- redis --><dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId><version>4.3.2</version></dependency> 此处使用的是Jedis&…

Buildroot 添加自定义模块-内置文件到文件系统

目录 概述实现步骤1. 创建包目录和文件结构2. 配置 Config.in3. 定义 cp_bin_files.mk4. 添加源文件install.shmy.conf 5. 配置与编译 概述 Buildroot 是一个高度可定制和模块化的嵌入式 Linux 构建系统&#xff0c;适用于从简单到复杂的各种嵌入式项目. buildroot的源码中bui…