鸿蒙 @ohos.arkui.observer (无感监听)

发布于:2025-03-16 ⋅ 阅读:(43) ⋅ 点赞:(0)

鸿蒙 @ohos.arkui.observer (无感监听)

在鸿蒙开发中,@ohos.arkui.observer 模块提供了一种强大的无感监听机制,允许开发者监听组件的状态变化、滚动事件、页面切换等事件。这些功能对于实现复杂的交互逻辑和优化性能非常有帮助。本文将详细介绍 @ohos.arkui.observer 模块的使用方法,并提供一些实际代码示例。


一、监听 NavDestination 组件的状态变化

@ohos.arkui.observer 模块提供了监听 NavDestination 组件状态变化的功能。通过 observer.on('navDestinationUpdate') 方法,可以监听 NavDestination 组件的状态变化。

示例代码

import { uiObserver as observer } from '@kit.ArkUI';

@Component
struct PageOne {
  build() {
    NavDestination() {
      Text("pageOne")
    }.title("pageOne")
  }
}

@Entry
@Component
struct Index {
  private stack: NavPathStack = new NavPathStack();

  @Builder
  PageBuilder(name: string) {
    PageOne()
  }

  aboutToAppear() {
    observer.on('navDestinationUpdate', (info) => {
      console.info('NavDestination state update', JSON.stringify(info));
    });
  }

  aboutToDisappear() {
    observer.off('navDestinationUpdate');
  }

  build() {
    Column() {
      Navigation(this.stack) {
        Button("push").onClick(() => {
          this.stack.pushPath({ name: "pageOne" });
        })
      }
      .title("Navigation")
      .navDestination(this.PageBuilder)
    }
    .width('100%')
    .height('100%')
  }
}

二、监听滚动事件

@ohos.arkui.observer 模块还提供了监听滚动事件的功能。通过 observer.on('scrollEvent') 方法,可以监听滚动事件的开始和结束。

示例代码

import { uiObserver as observer } from '@kit.ArkUI';

@Entry
@Component
struct Index {
  scroller: Scroller = new Scroller();
  options: observer.ObserverOptions = { id: "testId" };
  private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7];

  build() {
    Column() {
      Column() {
        Scroll(this.scroller) {
          Column() {
            ForEach(this.arr, (item: number) => {
              Text(item.toString())
                .width('90%')
                .height(150)
                .backgroundColor(0xFFFFFF)
                .borderRadius(15)
                .fontSize(16)
                .textAlign(TextAlign.Center)
                .margin({ top: 10 })
            }, (item: string) => item)
          }.width('100%')
        }
        .id("testId")
        .height('80%')
      }
      .width('100%')
      Row() {
        Button('UIObserver on')
          .onClick(() => {
            observer.on('scrollEvent', (info) => {
              console.info('scrollEventInfo', JSON.stringify(info));
            });
          })
        Button('UIObserver off')
          .onClick(() => {
            observer.off('scrollEvent');
          })
      }
      Row() {
        Button('UIObserverWithId on')
          .onClick(() => {
            observer.on('scrollEvent', this.options, (info) => {
              console.info('scrollEventInfo', JSON.stringify(info));
            });
          })
        Button('UIObserverWithId off')
          .onClick(() => {
            observer.off('scrollEvent', this.options);
          })
      }
    }
    .height('100%')
  }
}

三、监听页面切换事件

@ohos.arkui.observer 模块还提供了监听页面切换事件的功能。通过 observer.on('navDestinationSwitch') 方法,可以监听 Navigation 的页面切换事件。

示例代码

import { uiObserver as observer } from '@kit.ArkUI';

@Component
struct PageOne {
  build() {
    NavDestination() {
      Text("pageOne")
    }.title("pageOne")
  }
}

function callBackFunc(info: observer.NavDestinationSwitchInfo) {
  console.info(`testTag navDestinationSwitch from: ${JSON.stringify(info.from)} to: ${JSON.stringify(info.to)}`);
}

@Entry
@Component
struct Index {
  private stack: NavPathStack = new NavPathStack();

  @Builder
  PageBuilder(name: string) {
    PageOne()
  }

  aboutToAppear() {
    observer.on('navDestinationSwitch', this.getUIContext(), callBackFunc);
  }

  aboutToDisappear() {
    observer.off('navDestinationSwitch', this.getUIContext(), callBackFunc);
  }

  build() {
    Column() {
      Navigation(this.stack) {
        Button("push").onClick(() => {
          this.stack.pushPath({ name: "pageOne" });
        })
      }
      .title("Navigation")
      .navDestination(this.PageBuilder)
    }
    .width('100%')
    .height('100%')
  }
}

四、监听绘制指令下发

@ohos.arkui.observer 模块还提供了监听绘制指令下发的功能。通过 observer.on('willDraw') 方法,可以监听每一帧绘制指令的下发。

示例代码

import { uiObserver as observer } from '@kit.ArkUI';

@Entry
@Component
struct Index {
  willDrawCallback = () => {
    console.info("willDraw指令下发");
  }

  build() {
    Column() {
      Button('注册绘制指令下发监听')
        .onClick(() => {
          observer.on('willDraw', this.getUIContext(), this.willDrawCallback);
        })
    }
  }
}

五、总结

@ohos.arkui.observer 模块为鸿蒙开发提供了强大的无感监听功能,支持监听 NavDestination 组件的状态变化、滚动事件、页面切换事件以及绘制指令下发。通过这些功能,开发者可以实现复杂的交互逻辑和优化性能。希望本文能帮助你更好地理解和使用 @ohos.arkui.observer 模块。如果有任何问题或需要进一步讨论,欢迎随时交流!