在开发自定义滑动开关组件时,需要支持开启、关闭、加载中三种状态,且每种状态要有不同的动画效果。使用 ArkUI 声明式语法时,如何优雅地管理状态切换,并保证动画流畅性?
lovoydArkUI (方舟UI框架)
HarmonyOS 自定义控件中,如何用 ArkUI 声明式语法实现一个支持多状态切换的滑动开关组件?
仙银
系统 Toggle 组件只支持开/关两态,三态场景得自己画。核心思路:用枚举管状态,用 animateTo 驱动状态切换动画,加载态用 LoadingProgress 表达。
状态管理
用枚举定义三态,比裸 boolean 清晰得多:
enum SwitchState {
OFF = 0,
ON = 1,
LOADING = 2
}
状态流转:OFF → 点击 → LOADING → 异步完成 → ON;ON → 点击 → OFF。LOADING 期间禁止操作。
完整可运行示例
import { hilog } from '@kit.PerformanceAnalysisKit';
enum SwitchState {
OFF = 0,
ON = 1,
LOADING = 2
}
@Component
struct TriStateSwitch {
@State currentState: SwitchState = SwitchState.OFF;
private readonly trackWidth: number = 56;
private readonly trackHeight: number = 28;
private readonly thumbSize: number = 22;
private readonly thumbPadding: number = 3;
private thumbOffset(): number {
if (this.currentState === SwitchState.ON || this.currentState === SwitchState.LOADING) {
return this.trackWidth - this.thumbSize - this.thumbPadding;
}
return this.thumbPadding;
}
private trackColor(): ResourceColor {
if (this.currentState === SwitchState.ON) {
return '#007DFF';
}
if (this.currentState === SwitchState.LOADING) {
return '#FFB300';
}
return '#CCCCCC';
}
toggle() {
if (this.currentState === SwitchState.LOADING) {
return;
}
if (this.currentState === SwitchState.OFF) {
this.currentState = SwitchState.LOADING;
setTimeout(() => {
this.getUIContext()?.animateTo({ duration: 300, curve: Curve.EaseInOut }, () => {
this.currentState = SwitchState.ON;
});
}, 1500);
} else {
this.getUIContext()?.animateTo({ duration: 300, curve: Curve.EaseInOut }, () => {
this.currentState = SwitchState.OFF;
});
}
}
build() {
Stack() {
Row() {
if (this.currentState === SwitchState.LOADING) {
LoadingProgress()
.width(16)
.height(16)
.color(Color.White)
}
}
.width(this.thumbSize)
.height(this.thumbSize)
.borderRadius(this.thumbSize / 2)
.backgroundColor(Color.White)
.justifyContent(FlexAlign.Center)
.alignItems(VerticalAlign.Center)
.shadow({ radius: 2, color: '#33000000', offsetX: 0, offsetY: 1 })
.position({ x: this.thumbOffset(), y: this.thumbPadding })
.animation({
duration: 300,
curve: Curve.EaseInOut
})
}
.width(this.trackWidth)
.height(this.trackHeight)
.borderRadius(this.trackHeight / 2)
.backgroundColor(this.trackColor())
.animation({
duration: 300,
curve: Curve.EaseInOut
})
.onClick(() => {
this.toggle();
})
}
}
@Entry
@Component
struct Index {
@State statusText: string = 'OFF';
build() {
Column({ space: 30 }) {
Text('TriState Switch Demo')
.fontSize(20)
.fontWeight(FontWeight.Bold)
Row({ space: 16 }) {
Text('开关状态:')
.fontSize(16)
TriStateSwitch({ currentState: SwitchState.OFF })
Text(this.statusText)
.fontSize(16)
.fontWeight(FontWeight.Medium)
}
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
.alignItems(HorizontalAlign.Center)
.backgroundColor('#F1F3F5')
}
}
几个要点
为什么不用系统 Toggle + contentModifier? Toggle 的 contentModifier(API 12+)可以自定义滑块样式,但它的状态模型只有 isOn 布尔值,没有原生"加载中"态。硬要在 contentModifier 里判断第三方状态也可以,但状态和组件耦合太紧,不如直接自定义组件干净。参考:Toggle 组件文档
动画怎么保证流畅? 两个手段配合用:属性动画 .animation() 处理滑块位移和轨道颜色这类跟随状态变化的属性,写起来最省事;状态切换涉及多属性联动时用 this.getUIContext().animateTo() 把状态变更包在闭包里,控制时长和曲线。注意 animateTo 要通过 getUIContext() 调用,别用全局函数。参考:显式动画 animateTo
LOADING 态的处理:点击后先切到 LOADING(滑块右移 + 轨道变黄),用 setTimeout 模拟异步操作完成后切到 ON。实际项目里把 setTimeout 换成你的网络请求回调就行。LOADING 期间 toggle() 直接 return,避免重复触发。
如果只是想在系统 Toggle 的滑块上加个文字(比如"开/关"),用 contentModifier 就够了,官方 FAQ 有现成示例:如何在Toggle的圆形滑块上添加文字
Z用枚举管状态、animateTo 管过渡、animation 做属性渐变,三样配合就能实现。核心思路:状态驱动 UI,动画驱动过渡,别手动操作样式。
状态管理:用 enum 定义 OFF/ON/LOADING,拿 @State 持有当前值,状态变了 UI 自动刷新。三种状态分别对应不同的滑块位置、轨道颜色和内部组件(LoadingProgress vs 圆形滑块)。
动画策略:状态切换时用 animateTo 包裹赋值逻辑,闭包内的状态变化会自动带上过渡动画。从 OFF→LOADING 用 Curve.EaseOut(200ms 快速滑到中间态),LOADING→ON 用 springMotion 弹簧曲线(回弹手感),ON→OFF 也用弹簧曲线。弹簧曲线的 duration 不生效,动画时长由物理参数决定,手感更自然。
加载态:用 LoadingProgress 组件替掉圆形滑块,保留同样的偏移位置,加载完成后在 onFinish 回调里再切到 ON 状态。这样三种状态的视觉差异和过渡都有了。
代码已编译验证通过:
import { curves } from '@kit.ArkUI';
enum SwitchState {
OFF,
ON,
LOADING
}
@Component
struct MultiStateSwitch {
@State currentState: SwitchState = SwitchState.OFF;
@State thumbOffset: number = 0;
@State trackColor: string = '#CCCCCC';
@State thumbColor: string = '#FFFFFF';
@State trackWidth: number = 52;
@State trackHeight: number = 28;
@State thumbRadius: number = 12;
private thumbMaxOffset: number = 24;
build() {
Row() {
Stack() {
Row()
.width(this.trackWidth)
.height(this.trackHeight)
.borderRadius(this.trackHeight / 2)
.backgroundColor(this.trackColor)
.animation({ duration: 300, curve: Curve.EaseInOut })
if (this.currentState === SwitchState.LOADING) {
LoadingProgress()
.width(20)
.height(20)
.color('#FFFFFF')
.position({
x: this.thumbOffset + this.thumbRadius - 10 + 8,
y: (this.trackHeight - 20) / 2
})
.animation({ duration: 300, curve: Curve.EaseInOut })
} else {
Row()
.width(this.thumbRadius * 2)
.height(this.thumbRadius * 2)
.borderRadius(this.thumbRadius)
.backgroundColor(this.thumbColor)
.shadow({ radius: 4, color: '#33000000', offsetX: 0, offsetY: 2 })
.position({
x: this.thumbOffset + 8,
y: (this.trackHeight - this.thumbRadius * 2) / 2
})
.animation({ duration: 300, curve: Curve.EaseInOut })
}
}
.width(this.trackWidth)
.height(this.trackHeight)
.onClick(() => { this.toggle(); })
}
}
private toggle() {
if (this.currentState === SwitchState.LOADING) {
return;
}
if (this.currentState === SwitchState.ON) {
this.animateToOff();
} else {
this.animateToLoading();
}
}
private animateToLoading() {
this.getUIContext()?.animateTo({
duration: 200,
curve: Curve.EaseOut,
onFinish: () => { this.simulateAsyncComplete(); }
}, () => {
this.currentState = SwitchState.LOADING;
this.trackColor = '#FFA500';
this.thumbOffset = this.thumbMaxOffset;
});
}
private simulateAsyncComplete() {
setTimeout(() => {
this.getUIContext()?.animateTo({
duration: 300,
curve: curves.springMotion(0.6, 0.8)
}, () => {
this.currentState = SwitchState.ON;
this.trackColor = '#007DFF';
this.thumbOffset = this.thumbMaxOffset;
});
}, 1500);
}
private animateToOff() {
this.getUIContext()?.animateTo({
duration: 300,
curve: curves.springMotion(0.6, 0.8)
}, () => {
this.currentState = SwitchState.OFF;
this.trackColor = '#CCCCCC';
this.thumbOffset = 0;
});
}
}
@Entry
@Component
struct Index {
build() {
Column({ space: 30 }) {
Text('多状态滑动开关')
.fontSize(24)
.fontWeight(FontWeight.Bold)
MultiStateSwitch()
Text('点击开关:OFF → LOADING → ON,再次点击 → OFF')
.fontSize(14)
.fontColor('#666666')
.textAlign(TextAlign.Center)
.width('80%')
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
.alignItems(HorizontalAlign.Center)
}
}
几个要点:
-
animateTo 通过 UIContext 调用(this.getUIContext()?.animateTo),不是全局函数调用,这是官方推荐方式。相关文档:显式动画 animateTo
-
animation 属性只对写在它前面的属性生效,写在后面会直接跳变。所以 position/backgroundColor 等要放在 .animation() 前面。相关文档:属性动画 animation
-
弹簧曲线 curves.springMotion 让滑块有物理回弹感,比固定曲线更自然。相关文档:@AnimatableExtend 和弹簧曲线
-
如果页面上同时有大量动效组件,给容器加 .renderGroup(true) 可以合并绘制缓存,提升帧率。相关文档:优化动画性能
simulateAsyncComplete 里的 setTimeout 模拟异步请求,实际使用时替换成你的网络/IO 回调就行。我没在真机上验证弹簧曲线参数,你可以按手感调 springMotion 的 response 和 dampingFraction。
空瞳
补充一下真实请求接入时的状态闭环:上面的 setTimeout 示例会在 1200ms 后先把开关设为成功,再通知 onToggle;这只能演示动效,不能代表请求成功。
建议保留“已确认值、目标值、是否提交中”三类信息。用户确认后先进入加载态并立即发起请求;成功才提交目标值,失败恢复原值并提示。请求加序号,页面退出或新请求开始后,忽略已失效的旧结果。这样关闭失败时,也知道该回到开启状态。
animateTo 闭包只负责同步更新显示状态,网络请求放在外面;拿到有效结果后再做收尾动画,不用定时器或动画 onFinish 判定业务成功。Stage 模型下,组件内 this.getUIContext().animateTo 这套用法要求 API 11+。拖动还要处理 onActionCancel,取消后清除拖动标记并回到已确认位置,避免中断手势留下半开的滑块。
官方动画说明:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/arkts-animation-usage-guide
AI助手在 ArkUI 声明式范式下,实现多状态滑动开关的核心思路是:用单一枚举类型作为唯一状态源,通过 @State/@Link 驱动 UI,再配合显式动画(animateTo)与组件转场(transition)让每种状态切换都有独立的动效。相比用多个布尔值拼凑状态,枚举建模可以从根上避免"既开启又加载中"这类非法状态组合,也让动画分支逻辑更清晰。
状态与动画的设计思路
状态管理上,建议将"开启、关闭、加载中"定义为一个 enum,组件内部只维护两个状态变量:一个是与父组件同步的业务状态(@Link 或 V2 模型下的 @Param + @Event),另一个是滑块位移这类纯动画状态。所有交互(点击、拖拽)都收敛到一个统一入口方法中处理,加载中状态下直接拒绝新请求,避免状态竞争。
动画层面,三种状态各有侧重:关闭与开启之间的切换用弹簧曲线(curves.springMotion)驱动滑块位移和轨道变色,手感自然;进入加载态时,滑块与加载指示器(LoadingProgress)通过 TransitionEffect 做透明度加缩放的互斥转场,切换平滑不突兀;拖拽跟手阶段则直接更新位移状态、不插入显式动画,松手后再用 animateTo 弹回或落位,保证跟手不卡顿。
完整示例代码
以下代码适用于 API 12 及以上版本(HarmonyOS 5.x),可直接复制到 .ets 文件运行:
import { curves } from '@kit.ArkUI'
// 开关的三个互斥状态:用枚举统一建模,避免多个布尔值交叉判断产生非法状态
enum SwitchState {
OFF = 0,
ON = 1,
LOADING = 2
}
// 可复用的三态滑动开关组件
@Component
export struct TriStateSwitch {
// 对外业务状态:由父组件持有,组件内通过 @Link 双向同步
@Link state: SwitchState
// 状态落定后的对外回调,父组件可在此发起异步请求
onToggle?: (next: SwitchState) => void
// 内部动画状态:滑块当前位移(拖拽跟手时实时更新)
@State sliderX: number = 0
// 拖拽跟手标记:跟手阶段不插入显式动画
private isDragging: boolean = false
// 组件尺寸常量
private readonly trackWidth: number = 52
private readonly trackHeight: number = 30
private readonly thumbSize: number = 24
private readonly trackPadding: number = 3
// 滑块可移动的最大距离
private maxOffset(): number {
return this.trackWidth - this.thumbSize - this.trackPadding * 2
}
// 当前业务状态对应的滑块目标位置
private targetX(): number {
return this.state === SwitchState.ON ? this.maxOffset() : 0
}
aboutToAppear(): void {
// 初始化时直接落到目标位置,不播放动画
this.sliderX = this.targetX()
}
// 统一的状态切换入口:点击与拖拽结束都走这里
private requestToggle(): void {
if (this.state === SwitchState.LOADING) {
return // 加载中禁止再次触发,防止状态竞争
}
const next: SwitchState = this.state === SwitchState.ON ? SwitchState.OFF : SwitchState.ON
// 第一步:进入加载态,滑块以弹簧动画移动到目标位置
this.getUIContext()?.animateTo({ duration: 250, curve: curves.springMotion(0.34, 1.0) }, () => {
this.state = SwitchState.LOADING
this.sliderX = next === SwitchState.ON ? this.maxOffset() : 0
})
// 第二步:模拟异步操作,实际业务中应由网络请求结果决定最终落定状态
setTimeout(() => {
this.getUIContext()?.animateTo({ duration: 200, curve: curves.springMotion() }, () => {
this.state = next
})
if (this.onToggle) {
this.onToggle(next)
}
}, 1200)
}
build() {
Stack({ alignContent: Alignment.Start }) {
// 轨道背景:颜色随状态变化(关闭灰色,开启/加载中蓝色)
Row()
.width(this.trackWidth)
.height(this.trackHeight)
.borderRadius(this.trackHeight / 2)
.backgroundColor(this.state === SwitchState.OFF ? Color.Grey : '#007DFF')
if (this.state === SwitchState.LOADING) {
// 加载指示器:仅加载态渲染,出现/消失带透明度+缩放转场
LoadingProgress()
.width(this.thumbSize)
.height(this.thumbSize)
.color(Color.White)
.translate({ x: this.trackPadding + this.sliderX })
.transition(TransitionEffect.OPACITY.animation({ duration: 200 })
.combine(TransitionEffect.scale({ x: 0.6, y: 0.6 }).animation({ duration: 200 })))
} else {
// 滑块:关闭/开启态渲染,与加载指示器平滑互斥
Row()
.width(this.thumbSize)
.height(this.thumbSize)
.borderRadius(this.thumbSize / 2)
.backgroundColor(Color.White)
.translate({ x: this.trackPadding + this.sliderX })
.transition(TransitionEffect.OPACITY.animation({ duration: 200 })
.combine(TransitionEffect.scale({ x: 0.6, y: 0.6 }).animation({ duration: 200 })))
}
}
.width(this.trackWidth)
.height(this.trackHeight)
// 加载中屏蔽交互,防止动画被打断
.hitTestBehavior(this.state === SwitchState.LOADING ? HitTestMode.None : HitTestMode.Default)
.onClick(() => {
this.requestToggle()
})
// 拖拽手势:跟手移动,松手后按阈值决定切换或弹回
.gesture(
PanGesture({ fingers: 1, distance: 1 })
.onActionStart(() => {
if (this.state === SwitchState.LOADING) {
return
}
this.isDragging = true
})
.onActionUpdate((event: GestureEvent) => {
if (!this.isDragging) {
return
}
// 以当前目标位置为基准累加偏移,直接更新状态实现跟手(不插入显式动画)
const raw: number = this.targetX() + event.offsetX
this.sliderX = Math.min(this.maxOffset(), Math.max(0, raw))
})
.onActionEnd(() => {
if (!this.isDragging) {
return
}
this.isDragging = false
// 位移超过一半即视为切换意图
const shouldOn: boolean = this.sliderX > this.maxOffset() / 2
const currentOn: boolean = this.state === SwitchState.ON
if (shouldOn !== currentOn) {
this.requestToggle()
} else {
// 未达到切换阈值,弹簧曲线弹回原位
this.getUIContext()?.animateTo({ curve: curves.springMotion() }, () => {
this.sliderX = this.targetX()
})
}
})
)
}
}
// 演示页面
@Entry
@Component
struct Index {
@State switchState: SwitchState = SwitchState.OFF
build() {
Column({ space: 24 }) {
TriStateSwitch({
state: this.switchState,
onToggle: (next: SwitchState) => {
// 实际业务中可在此处发起异步请求,并根据结果回写状态
console.info(`开关落定为: ${SwitchState[next]}`)
}
})
Text(`当前状态: ${SwitchState[this.switchState]}`)
.fontSize(16)
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}
补充说明与流畅性要点
关于状态管理的"优雅"之处,关键在于三点:一是用枚举做单一数据源,build 中所有 UI 分支(轨道颜色、滑块与加载指示器的互斥渲染)都只依赖这一个状态,逻辑可预测;二是所有交互收敛到 requestToggle 一个入口,天然规避了并发触发导致的状态错乱;三是加载中的落定结果由异步回调决定,组件只负责呈现,业务决策权留给父组件,职责清晰。
保证动画流畅性有几个实践要点。位移一律使用 translate 而不是 margin 或 width,因为 translate 只触发绘制侧的仿射变换,不引起重新布局,开销最小。拖拽跟手阶段直接修改状态、不包 animateTo,避免每帧插入动画调度;只有松手后的落位/弹回才用显式动画。曲线选择上,curves.springMotion() 默认参数即为系统推荐的物理弹簧曲线,速度连续无跳变,比固定时长的 Ease 曲线更适合开关类交互。另外,建议使用 this.getUIContext()?.animateTo(...) 而非全局 animateTo,前者绑定了当前 UI 上下文,是官方当前推荐写法,可避免 UI 上下文不明确的问题。
如果项目已使用状态管理 V2 模型,可将组件改造为 @ComponentV2:外部状态用 @Param 接收、@Event 回调通知变更,内部动画状态用 @Local,语义更严格。滑块与加载指示器的互斥转场若觉得 if/else 分支冗余,也可以改用 Stack 叠放两层并用 opacity 属性动画控制显隐,两种方式动画效果等价,按团队习惯选择即可。
- 为了保障您的信息安全,请勿上传您的敏感个人信息(如您的密码等信息)和您的敏感资产信息(如关键源代码、签名私钥、调试安装包、业务日志等信息),且您需自行承担由此产生的信息泄露等安全风险。
- 如您发布的内容为转载内容,请注明内容来源。
我要提问题
HarmonyOS Slider组件如何自定义滑动时弹出的气泡框样式 (API12+)
HarmonyOS ARKUI_NODE_SCROLL组件PC端不响应横向滑动 (API12+)
HarmonyOS 使用swiper滑动的时候,滑动的阈值是多少,切换阈值的时候不灵敏(API12+)
HarmonyOS 如何实现滑动展开收起功能(API12+)
HarmonyOS 如何使用ArkUI构建异形自定义组件?(API12+)
HarmonyOS 应用内如何跳转设置消息通知开关(API12+)
HarmonyOS 有没有滑动多选的组件可以用 (API12+)
HarmonyOS 如何实现滑动两次退出应用(API12+)




































苏公安网备 32011402010933号