鸿蒙Next如何自定义标签页

news/2025/3/1 5:18:23/

前言

项目需求是展示标签,标签的个数不定,一行展示不行就自行换行。但是,使用鸿蒙原生的 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/news/1575690.html

相关文章

PHP操作redis

目录 一、安装PHP的redis扩展 1、linux下安装php的redis扩展 2、windows下安装php的redis扩展 二、PHP操作redis 1、面向过程操作redis 2、面向对象操作redis 一、安装PHP的redis扩展 1&#xff09;PHP的redis扩展有2个&#xff0c;分别是phpredis和predis扩展&#xff…

Android Audio实战——音频相关基础概念(附)

Android Audio 开发其实就是媒体源数字化的过程,通过将声波波形信号通过 ADC 转换成计算机支持的二进制的过程叫做音频采样 (Audio Sampling)。采样 (Sampling) 的核心是把连续的模拟信号转换成离散的数字信号。 一、声音的属性 1、响度 (Loudness) 响度是指人类可以感知到的…

Metal 学习笔记六:坐标空间

要在网格上轻松找到一个点&#xff0c;您需要一个坐标系。例如&#xff0c;如果网格恰好是您的 iPhone 15 屏幕&#xff0c;则中心点可能是 x&#xff1a;197、y&#xff1a;426。但是&#xff0c;该点可能会有所不同&#xff0c;具体取决于它所处的空间。 在上一章中&#xf…

Nuxt.js 3【详解】服务器 Server

Nuxt.js 是一个全栈框架&#xff0c;可以在一个项目中&#xff0c;同时完成前端和后端的开发。 服务器架构 Nuxt.js 的服务端由 Nitro 实现&#xff0c;Nitro 由基于 H3 实现。 Nitro 官网 https://nitro.build/guideH3 官网 https://h3.unjs.io/guide 接口路由 基于文件目录自…

JAVA面试常见题_基础部分_Mysql调优

性能监控 使用show profile查询剖析工具&#xff0c;可以指定具体的type 此工具默认是禁用的&#xff0c;可以通过服务器变量在绘画级别动态的修改 set profiling1; 当设置完成之后&#xff0c;在服务器上执行的所有语句&#xff0c;都会测量其耗费的时间和其他一些查询执行状…

C++-第十二章: AVL树

目录 第一节&#xff1a;AVL树的特征 第二节&#xff1a;实现思路 2-1.插入 2-1-1.右单旋 2-1-2.左单旋 2-1-3.左右双旋 2-1-4.右左双旋 2-1-5.总结 2-2.删除 第三节&#xff1a;代码实现 3-1.Node类 3-2.AVLTree类 3-2-1.Insert函数 3-2-2.Height函数 3-2-3.Balance函数 3-…

【超详细】神经网络的可视化解释

《------往期经典推荐------》 一、AI应用软件开发实战专栏【链接】 项目名称项目名称1.【人脸识别与管理系统开发】2.【车牌识别与自动收费管理系统开发】3.【手势识别系统开发】4.【人脸面部活体检测系统开发】5.【图片风格快速迁移软件开发】6.【人脸表表情识别系统】7.【…

AF3 pair_sequences函数解读

AlphaFold3 msa_pairing模块的pair_sequences函数的核心目标是基于 MSA(多序列比对)中的物种信息,在多条链之间建立 MSA 配对索引,从而帮助 AlphaFold3 捕捉共进化信息,提升蛋白复合物预测的准确性。函数pair_sequences 通过调用 _make_msa_df、 _create_species_dict 以…