中国优质的IT技术网站
专业IT技术创作平台
IT职业在线教育平台
一、事件 组件可见区域变化事件是组件在屏幕中的显示区域面积变化时触发的事件,提供了判断组件是否完全或部分显示在屏幕中的能力,适用于广告曝光埋点之类的场景。(api9开始支持) 二、示例 代码:
@Entry @Component struct Index { scroller: Scroller = new Scroller() private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] @State testTextStr: string = 'test' @State testRowStr: string = 'test' build() { Column() { Column() { Text(this.testTextStr) .fontSize(20) .fontColor(Color.White) .margin(10) Text(this.testRowStr) .fontSize(20) .fontColor(Color.White) } .width('100%') .height(100) .backgroundColor(Color.Black) Scroll(this.scroller) { Column() { Text("测试文本可见变化") .fontSize(20) .height(200) .width(300) .textAlign(TextAlign.Center) .margin({ top: 50, bottom: 20 }) .backgroundColor(Color.Green) // 通过设置ratios为[0.0, 1.0],实现当组件完全显示或完全消失在屏幕中时触发回调 .onVisibleAreaChange([0.0, 1.0], (isVisible: boolean, currentRatio: number) => { console.info('Test Text isVisible: ' + isVisible + ', currentRatio:' + currentRatio) if (isVisible && currentRatio >= 1.0) { console.info('Test Text is fully visible. currentRatio:' + currentRatio) this.testTextStr = '测试文本是可见的' } if (!isVisible && currentRatio <= 0.0) { console.info('Test Text is completely invisible.') this.testTextStr = '测试文本是不可见的' } }) Row() { Text('测试组件Row可见变化') .fontSize(20) .margin({ bottom: 20 }) .width(300) .textAlign(TextAlign.Center) } .height(200) .backgroundColor(Color.Yellow) .onVisibleAreaChange([0.0, 1.0], (isVisible: boolean, currentRatio: number) => { console.info('Test Row isVisible:' + isVisible + ', currentRatio:' + currentRatio) if (isVisible && currentRatio >= 1.0) { console.info('Test Row is fully visible.') this.testRowStr = '测试组件Row是可见的' } if (!isVisible && currentRatio <= 0.0) { console.info('Test Row is is completely invisible.') this.testRowStr = '测试组件Row是不可见的' } }) ForEach(this.arr, (item) => { Text(item.toString()) .width('90%') .height(150) .backgroundColor(0xFFFFFF) .borderRadius(15) .fontSize(16) .textAlign(TextAlign.Center) .margin({ top: 10 }) }, item => item) }.width('100%') } .backgroundColor(0x317aff) .scrollable(ScrollDirection.Vertical) .scrollBar(BarState.On) .scrollBarColor(Color.Gray) .scrollBarWidth(30) .onScroll((xOffset: number, yOffset: number) => { console.info(xOffset + ' ' + yOffset) }) .onScrollEdge((side: Edge) => { console.info('To the edge') }) .onScrollEnd(() => { console.info('Scroll Stop') }) }.width('100%').height('100%').backgroundColor(0xDCDCDC) } }
完整代码地址:https://gitee.com/jltfcloudcn/jump_to/tree/master/VisibleAreaChange
微信扫码分享