#跟着若城学鸿蒙# 角标组件(Badge)
·
角标(Badge)用于在界面中对某个元素进行消息或状态提示。常见应用场景包括未读消息数、小红点提醒、功能标签等。ArkUI 中的 Badge 组件支持数字和文本两种形式,且可自定义位置与样式。
1 构造方法
interface BadgeInterface {
(params: BadgeParamWithNumber): BadgeAttribute;
(params: BadgeParamWithString): BadgeAttribute;
}
-
BadgeParam(公共参数)
-
position?: BadgePositionBadgePosition.Left:左侧纵向居中BadgePosition.Right:右侧纵向居中BadgePosition.RightTop(默认):右上角
-
style: BadgeStylecolor?: ResourceColor(文本颜色,默认白色)fontSize?: number(字体大小,默认 10vp)badgeSize?: number(角标直径)badgeColor?: ResourceColor(背景色,默认红色)
-
-
数字形态:
interface BadgeParamWithNumber extends BadgeParam { count: number; // 显示的数字 maxCount?: number; // 最大值,超过后显示 “maxCount+” } -
文本形态:
interface BadgeParamWithString extends BadgeParam { value: string; // 显示的文本内容 }
2 基本示例
下例展示了 小红点、数字、文本 三种常用场景。
@Entry @Component
struct BadgeBasicDemo {
build() {
Row({ space: 24, alignItems: VerticalAlign.Center }) {
// 1. 小红点
Badge({
value: ' ',
position: BadgePosition.RightTop,
style: { badgeSize: 8, badgeColor: Color.Red }
}) {
Icon(Icons.Mail)
.size({ width: 40, height: 40 });
}
.size({ width: 40, height: 40 });
// 2. 数字提示
Badge({
count: 5,
maxCount: 99,
position: BadgePosition.RightTop,
style: { color: Color.White, fontSize: 12, badgeColor: Color.Red }
}) {
Button("通知")
.size({ width: 100, height: 44 });
}
// 3. 文本标签
Badge({
value: 'NEW',
position: BadgePosition.Right,
style: { color: Color.White, fontSize: 10, badgeColor: Color.Blue }
}) {
Text("功能")
.padding({ horizontal: 12, vertical: 8 })
.backgroundColor(Color.Gray);
}
}
.padding(20);
}
}
3 数字溢出处理
当 count 大于 maxCount 时,将以 "maxCount+" 形式显示。
Badge({
count: 120,
maxCount: 99,
position: BadgePosition.RightTop,
style: { color: Color.White, fontSize: 12, badgeColor: Color.Red }
}) {
Text("邮件")
.padding({ horizontal: 16, vertical: 8 })
.backgroundColor("#aabbcc");
}
效果:角标显示为
“99+”。
4 文本角标示例
Badge({
value: "HOT",
position: BadgePosition.Left,
style: { color: Color.White, fontSize: 10, badgeColor: Color.Orange }
}) {
Text("专题")
.padding({ horizontal: 10, vertical: 6 })
.backgroundColor("#ddeeff");
}
5 完整交互示例
综合运用状态管理,演示数字与文本角标的动态更新。
@Entry @Component
struct BadgeInteractiveDemo {
@State count: number = 0;
@State label: string = "Go";
build() {
Column({ space: 30, 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.label,
style: { color: Color.White, fontSize: 10, badgeColor: Color.Purple }
}) {
Text("Toggle")
.padding({ horizontal: 14, vertical: 8 })
.backgroundColor(Color.Gray)
.onClick(() => {
this.label = this.label === "Go" ? "OK" : "Go";
});
}
}
.padding(40);
}
}
6 总结
- 形式灵活:既可显示数字,也可显示任意文本或小红点。
- 位置可控:支持左、中、右、右上等多种对齐。
- 样式丰富:自定义大小、色彩、字体。
- 状态联动:与
@State配合,无缝实现动态更新。
通过对 Badge 的掌握,您可以为应用中的任何元素添加醒目的消息提示,从而提升用户体验与交互效果。
更多推荐

所有评论(0)