HarmonyOS 鸿蒙Next Text实现展开收起
HarmonyOS 鸿蒙Next Text实现展开收起
text段落文本展示三行,后面以省略号加’‘展开’'字样结尾,点击展开后,剩余文本全部展示.
3 回复
参考demo
~~~
import measure from '[@ohos](/user/ohos).measure'
[@Entry](/user/Entry)
[@Component](/user/Component)
struct TextCollapseTest {
[@State](/user/State) rawTitle: string = "1月16日,国务院新闻办公室举行新闻发布会,介绍2024年春运形势及工作安排。从2月9日(除夕)00:00到2月17日(正月初八)24:00,免费9天。"
[@State](/user/State) title: string = this.rawTitle
[@State](/user/State) suffixStr: string = ""
expanded: Boolean = true
titleWidth: number = 350
needProcess: boolean = true
ellipsis: string = "..."
EXPAND_STR: string = "展开"
COLLAPSE_STR: string = "收起"
MAX_LINES: number = 3;
aboutToAppear(): void {
this.process();
}
process(): void {
if (this.expanded) {
this.collapseText();
} else {
this.expandText();
}
}
//展开文本
expandText(): void {
console.log('testTag: ' + this.needProcess);
if (this.needProcess) {
this.suffixStr = this.COLLAPSE_STR;
this.expanded = true;
this.title = this.rawTitle;
}
}
//收起文本
collapseText(): void {
if (!this.needProcess) {
return;
}
let titleSize: SizeOptions = measure.measureTextSize({
textContent: this.rawTitle,
constraintWidth: this.titleWidth,
fontSize: 30
})
let twoLineSize: SizeOptions = measure.measureTextSize({
textContent: this.rawTitle,
constraintWidth: this.titleWidth,
fontSize: 30,
maxLines: this.MAX_LINES
})
//文本未超过限制行数,不进行展开、收起处理
if ((titleSize.height as number) == (twoLineSize.height as number)) {
this.needProcess = false;
return;
}
console.log('test row height:' + titleSize.height)
console.log('test twoLineSize height:' + twoLineSize.height)
let clipTitle: string = this.rawTitle
this.suffixStr = this.EXPAND_STR;
while ((titleSize.height as number) > (twoLineSize.height as number)) {
this.expanded = true;
// 可以修改其他计算算法提高性能
clipTitle = clipTitle.substring(0, clipTitle.length - 1);
titleSize = measure.measureTextSize({
textContent: clipTitle + this.ellipsis + this.suffixStr,
constraintWidth: this.titleWidth,
fontSize: 30
})
console.log("test while clipTitle:" + clipTitle)
console.log("test while clipTitle height:" + titleSize.height)
}
console.log("test clipTitle:" + clipTitle)
this.title = clipTitle + this.ellipsis
this.expanded = false;
}
build() {
Row() {
Column() {
Text() {
Span(this.title)
if (this.needProcess) {
Span(this.suffixStr)
.fontColor(Color.Orange)
.onClick((event) => {
this.process();
})
}
}
.fontSize(30)
.fontWeight(FontWeight.Bold)
.id("title")
.width(this.titleWidth)
}
.width('100%')
}
.height('100%')
}
}
1楼demo ok
在HarmonyOS(鸿蒙)系统中实现文本内容的“展开”与“收起”功能,通常涉及UI布局的动态调整以及文本视图的可见性控制。以下是一个基本的实现思路:
-
UI布局设计:使用
StackLayout
或LinearLayout
等布局容器,将完整文本视图和摘要文本视图(或按钮)叠加放置。初始状态下,摘要文本或“展开”按钮可见,完整文本视图隐藏。 -
状态控制:定义一个布尔变量来跟踪当前文本是展开还是收起状态。当用户点击“展开”或“收起”按钮时,切换该变量的值,并据此调整文本视图的可见性。
-
动画效果(可选):为了提升用户体验,可以在文本视图可见性切换时添加平滑的动画效果,如渐变显示或隐藏。
-
事件处理:在按钮的点击事件中,编写逻辑来切换文本视图的状态,并更新UI。
示例代码因篇幅限制无法展示,但上述步骤应能帮助你在HarmonyOS应用中实现基本的文本展开与收起功能。如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html 。