#跟着若城学鸿蒙# 玩转角标 (Badge):让消息提示更抢眼
·
角标(Badge)可谓是“消息到啦”的万能利器,无论是未读数、最新标签,还是小红点提醒,都能轻松搞定。下面我们用轻松的方式,带你快速掌握 ArkUI 的 Badge 组件。
一、Badge 能力速览
- 数字角标:
.count
+.maxCount
,自动99+
- 文本角标:
.value
支持任意字符串 - 小红点:空字符串或单空格即可
- 位置可选:左侧、中间、右侧、右上…
- 样式自由:大小、颜色、字体随心定
二、基本用法:给子组件包一层
@Entry @Component
struct BadgeDemo {
build() {
Row({ space: 30, alignItems: VerticalAlign.Center }) {
// ① 小红点
Badge({
value: ' ',
position: BadgePosition.RightTop,
style: { badgeSize: 8, badgeColor: Color.Red }
}) {
Icon(Icons.Mail) // 任意子组件
.size({ width: 40, height: 40 });
}
// ② 文字标签
Badge({
value: 'NEW',
position: BadgePosition.RightTop,
style: { color: Color.White, fontSize: 10, badgeColor: Color.Blue }
}) {
Text("消息")
.fontSize(18)
.padding({ horizontal: 12, vertical: 8 })
.backgroundColor(Color.Gray);
}
// ③ 数字提示
Badge({
count: 42,
maxCount: 99,
position: BadgePosition.RightTop,
style: { color: Color.White, fontSize: 12, badgeColor: Color.Red }
}) {
Button("通知")
.size({ width:120, height:48 });
}
}
.padding(20);
}
}
Tips
position
可选:Left
、Right
、RightTop
(默认)style
还能调badgeSize
、fontSize
、badgeColor
……
三、数字角标进阶
当消息数过大时,自动溢出显示 maxCount+
:
Badge({
count: 120,
maxCount: 99,
position: BadgePosition.RightTop,
style: { badgeSize: 20, badgeColor: Color.Red }
}) {
Text("邮件")
.padding(12)
.backgroundColor("#aabbcc");
}
效果:显示为
99+
,再也不怕突然冒出千条未读。
四、纯文字角标示例
想显示任意标签?文字轻松驾驭:
Badge({
value: "HOT",
position: BadgePosition.Left,
style: { color: Color.White, fontSize: 10, badgeColor: Color.Orange }
}) {
Text("专题")
.padding({ horizontal: 10, vertical: 6 })
.backgroundColor("#ddeeff");
}
五、完整交互示例
增、删、切换一把抓:
@Entry @Component
struct InteractiveBadge {
@State count: number = 0;
@State tag: string = "Go";
build() {
Column({ space: 20, alignItems: HorizontalAlign.Center }) {
// 按钮点击增加数字角标
Badge({
count: this.count,
maxCount: 99,
style: { color: Color.White, fontSize: 12, badgeColor: Color.Red }
}) {
Button("Add")
.onClick(() => this.count++)
.size({ width: 100, height: 50 });
}
// 文本控件切换文字角标
Badge({
value: this.tag,
style: { color: Color.White, fontSize: 10, badgeColor: Color.Purple }
}) {
Text("Label")
.padding({ horizontal: 14, vertical: 8 })
.backgroundColor(Color.Gray)
.onClick(() => this.tag = this.tag === "Go" ? "OK" : "Go");
}
}
.padding(30);
}
}
小结:
- 点击“Add”,数字不断累加;
- 点击“Label”,角标文字在
Go
/OK
之间切换。
六、总结
- 一行代码包裹:想贴谁就贴谁,
Badge({...}) { 子组件 }
- 丰富的 API:
count
、value
、position
、style
…… - 零配置小红点:
value: ' '
即可 - 随心交互:搭配状态,轻松响应点击,消息提示不遗漏
快给你的 App 加上角标,一秒提升「消息感」与「可用度」吧!
更多推荐
所有评论(0)