HarmonyOS 鸿蒙Next中组件可见区域变化事件
HarmonyOS 鸿蒙Next中组件可见区域变化事件
组件可见区域变化事件是组件在屏幕中的显示区域面积变化时触发的事件,提供了判断组件是否完全或部分显示在屏幕中的能力,适用于广告曝光埋点之类的场景、页面需要返回及时刷新等。
1.常用方法
(1)onVisibleAreaChange(ratios: Array, event: VisibleAreaChangeCallback): T
(2)使用案例
Text("Test Text Visible Change")
.fontSize(20)
.height(200)
.margin({ top: 50, bottom: 20 })
.backgroundColor(Color.Green)
// 通过设置ratios为[0.0, 1.0],实现当组件完全显示或完全消失在屏幕中时触发回调。
.onVisibleAreaChange([0.0, 1.0], (isExpanding: boolean, currentRatio: number) => {
console.info('Test Text isExpanding: ' + isExpanding + ', currentRatio:' + currentRatio)
if (isExpanding && currentRatio >= 1.0) {
console.info('Test Text is fully visible. currentRatio:' + currentRatio)
this.testTextStr = 'Test Text is fully visible'
}
if (!isExpanding && currentRatio <= 0.0) {
console.info('Test Text is completely invisible.')
this.testTextStr = 'Test Text is completely invisible'
}
})
2.升级版方法
(1)onVisibleAreaApproximateChange(options: VisibleAreaEventOptions, event: VisibleAreaChangeCallback | undefined): void
注:与onVisibleAreaChange接口存在如下差异,onVisibleAreaChange在每一帧都会进行可见区域比例的计算,如果注册节点太多,系统功耗存在劣化。此接口降低了可见区域比例计算的频度,计算间隔由VisibleAreaEventOptions的expectedUpdateInterval参数决定。
(2)使用案例
Text("Test Text Visible Change")
.fontSize(20)
.height(200)
.margin({ top: 50, bottom: 20 })
.backgroundColor(Color.Green)
// 通过设置ratios为[0.0, 1.0],实现当组件完全显示或完全消失在屏幕中时触发回调。
.onVisibleAreaApproximateChange({ratios: [0.0, 1.0], expectedUpdateInterval: 1000}, (isExpanding: boolean, currentRatio: number) => {
console.info('Test Text isExpanding: ' + isExpanding + ', currentRatio:' + currentRatio)
if (isExpanding && currentRatio >= 1.0) {
console.info('Test Text is fully visible. currentRatio:' + currentRatio)
this.testTextStr = 'Test Text is fully visible'
}
if (!isExpanding && currentRatio <= 0.0) {
console.info('Test Text is completely invisible.')
this.testTextStr = 'Test Text is completely invisible'
}
})
更多关于HarmonyOS 鸿蒙Next中组件可见区域变化事件的实战教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS Next中,组件可见区域变化事件通过onVisibleAreaChange
回调实现。该事件在组件的可见比例达到设定阈值时触发,阈值范围[0,1]。使用时需在组件上设置visibleArea
属性,如visibleArea({ ratios: \[0.5\] })
表示当50%可见时触发。回调参数包含当前可见比例和组件实例。该API适用于List、Grid等滚动容器中的组件,用于实现懒加载、曝光统计等功能。注意:事件触发依赖框架的渲染管线,高频滚动时可能有性能损耗。
更多关于HarmonyOS 鸿蒙Next中组件可见区域变化事件的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
关于HarmonyOS Next中的组件可见区域变化事件,我来补充几点关键信息:
-
性能优化建议: 对于需要监控大量组件可见状态的场景,推荐使用
onVisibleAreaApproximateChange
,通过设置expectedUpdateInterval
(单位ms)可以显著降低性能开销。典型值建议设置在300-1000ms区间。 -
实际应用场景:
- 广告曝光统计:当
ratio≥0.5
时可视为有效曝光 - 懒加载:组件进入可视区域再加载内容
- 视频自动播放:完全可见时(
autoPlayRatio=1.0
)触发播放
- 注意事项:
- 滚动容器内的组件需要确保
clip
属性为false
- 组件必须设置具体尺寸(
width
/height
) - 回调函数应避免耗时操作
- 参数说明:
ratios
数组支持设置多个阈值点(如[0.2,0.5,1.0]
)isExpanding
表示可见比例变化趋势currentRatio
是当前实际可见比例(0.0-1.0)
这两种API为开发者提供了灵活的可见性检测方案,可根据具体场景选择实时性优先或性能优先的方案。