鸿蒙5.0开发进阶:API ArkUI框架-ArkTS组件(焦点事件)

往期鸿蒙全套实战文章必看:(文中附带全栈鸿蒙学习资料)


焦点事件

焦点事件指页面焦点在可获焦组件间移动时触发的事件,组件可使用焦点事件来处理相关逻辑。

说明

  • 从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。

  • 目前仅支持通过外接键盘的tab键、方向键触发。不支持嵌套滚动组件场景按键走焦。

  • 存在默认交互逻辑的组件例如ButtonTextInput等,默认即为可获焦,TextImage等组件默认状态为不可获焦,不可获焦状态下,无法触发焦点事件,需要设置focusable属性为true才可触发。

  • 焦点开发参考焦点开发指南

onFocus

onFocus(event: () => void)

当前组件获取焦点时触发的回调。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

onBlur

onBlur(event:() => void)

当前组件失去焦点时触发的回调。

元服务API: 从API version 11开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

示例

该示例展示了组件获焦和失焦的情况,按钮获焦和失焦时会改变按钮的颜色。

// xxx.ets
@Entry
@Component
struct FocusEventExample {
@State oneButtonColor: string = '#FFC0CB'
@State twoButtonColor: string = '#87CEFA'
@State threeButtonColor: string = '#90EE90'

build() {
Column({ space: 20 }) {
// 通过外接键盘的上下键可以让焦点在三个按钮间移动,按钮获焦时颜色变化,失焦时变回原背景色
Button('First Button')
.backgroundColor(this.oneButtonColor)
.width(260)
.height(70)
.fontColor(Color.Black)
.focusable(true)
.onFocus(() => {
this.oneButtonColor = '#FF0000'
})
.onBlur(() => {
this.oneButtonColor = '#FFC0CB'
})
Button('Second Button')
.backgroundColor(this.twoButtonColor)
.width(260)
.height(70)
.fontColor(Color.Black)
.focusable(true)
.onFocus(() => {
this.twoButtonColor = '#FF0000'
})
.onBlur(() => {
this.twoButtonColor = '#87CEFA'
})
Button('Third Button')
.backgroundColor(this.threeButtonColor)
.width(260)
.height(70)
.fontColor(Color.Black)
.focusable(true)
.onFocus(() => {
this.threeButtonColor = '#FF0000'
})
.onBlur(() => {
this.threeButtonColor = '#90EE90'
})
}.width('100%').margin({ top: 20 })
}
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值