Switch 開關
開關控制項。點選翻轉開合態,支援停用與載入中遮罩。
契約源:
lh-ui-core/specs/switch.json· 黃金用例:lh-ui-core/cases/switch.json(6 條,已翻譯為 hypium 測試)
基本用法
checked 受控,點選翻轉並觸發 onChange 攜帶新開合態。滑塊位移動畫取 motion.duration.base。
HTML 模擬預覽(鴻蒙 / ArkUI 外觀),非真機渲染
typescript
LhSwitch({
checked: this.enabled,
onChange: (checked: boolean) => { this.enabled = checked },
})尺寸
三檔尺寸映射到 switch.width / switch.height 令牌;軌道圓角與滑塊偏移隨高度換算。
HTML 模擬預覽(鴻蒙 / ArkUI 外觀),非真機渲染
狀態
disabled 與 loading 都阻止切換(黃金用例 loading-blocks-change); 載入中時軌道中央顯示平台指示器。
HTML 模擬預覽(鴻蒙 / ArkUI 外觀),非真機渲染
API
Props
| 屬性 | 說明 | 型別 | 預設值 |
|---|---|---|---|
checked | 是否開啟 | boolean | false |
disabled | 是否停用;停用時不觸發 onChange | boolean | false |
loading | 是否載入中;載入時不觸發 onChange,軌道顯示指示器 | boolean | false |
size | 開關尺寸,映射到尺寸令牌 | LhSwitchSize | Medium |
onChange | 點選切換時觸發,攜帶新開合態 | (checked: boolean) => void | 空函式 |
LhSwitchSize
| 值 | width | height |
|---|---|---|
Small | switch.width.small(36vp) | switch.height.small(20vp) |
Medium | switch.width.medium(44vp) | switch.height.medium(24vp) |
Large | switch.width.large(52vp) | switch.height.large(28vp) |
開軌底色 color.primary.default;關軌底色 color.background.disabled; 滑塊 color.onPrimary,直徑 = 高度 − 2 × switch.gap。
令牌對照
| 令牌 | 用途 |
|---|---|
switch.width.{small,medium,large} | 三檔軌道寬度 |
switch.height.{small,medium,large} | 三檔軌道高度(圓角與滑塊偏移據此換算) |
switch.gap | 滑塊與軌道之間的留白(2vp) |
color.primary.default | 開軌底色 |
color.background.disabled | 關軌底色 |
color.onPrimary | 滑塊色 |
color.disabled.* | 停用態色 |
motion.duration.base | 滑塊位移動畫時長(300ms) |
黃金用例對照
cases/switch.json 的 6 條斷言與 hypium 測試的對應關係(entry/src/test/Switch.test.ets):
| case id | 斷言 | 本地測試 |
|---|---|---|
tap-toggles-and-emits-onchange | 點選翻轉並觸發 onChange | enabled_is_interactive |
tap-checked-turns-off | 開啟態點選關閉 | thumb_offset_follows_checked(位移斷言) |
disabled-blocks-change | 停用態不觸發 onChange | disabled_is_not_interactive |
loading-blocks-change | 載入態不觸發 onChange | loading_is_not_interactive |
checked-uses-primary-token | 開軌消費主色令牌 | checked_uses_primary_token |
unchecked-uses-border-token | 關軌消費停用底色令牌 | unchecked_uses_border_token |
另有暗色專項:dark_colors_come_from_dark_tokens / dimensions_are_identical_in_dark_mode。 執行:DevEco Studio 右鍵 entry/src/test → Run Tests。

