openharmony 鸿蒙 js-apis-arkui-observer

2025-06-12 浏览 (1)

@ohos.arkui.observer (Observer)

The Observer module provides APIs for listening for UI component behavior changes.

NOTE

The initial APIs of this module are supported since API version 11. Updates will be marked with a superscript to indicate their earliest API version.

Modules to Import

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

NavDestinationState

Describes the state of the NavDestination component.

System capability: SystemCapability.ArkUI.ArkUI.Full

NameValueDescription
ON_SHOWN0The NavDestination component is displayed. Atomic service API: This API can be used in atomic services since API version 12.
ON_HIDDEN1The NavDestination component is hidden. Atomic service API: This API can be used in atomic services since API version 12.
ON_APPEAR12+2The NavDestination component is attached to the component tree. Atomic service API: This API can be used in atomic services since API version 12.
ON_DISAPPEAR12+3The NavDestination component is detached from the component tree. Atomic service API: This API can be used in atomic services since API version 12.
ON_WILL_SHOW12+4The NavDestination is about to be displayed. Atomic service API: This API can be used in atomic services since API version 12.
ON_WILL_HIDE12+5The NavDestination component is about to be hidden. Atomic service API: This API can be used in atomic services since API version 12.
ON_WILL_APPEAR12+6The NavDestination component is about to be mounted to the component tree. Atomic service API: This API can be used in atomic services since API version 12.
ON_WILL_DISAPPEAR12+7The NavDestination component is about to be unmounted from the component tree. Atomic service API: This API can be used in atomic services since API version 12.
ON_ACTIVE18+8The NavDestination component is active. Atomic service API: This API can be used in atomic services since API version 18.
ON_INACTIVE18+9The NavDestination component is inactive. Atomic service API: This API can be used in atomic services since API version 18.
ON_BACKPRESS12+100The back button is pressed on the NavDestination component. Atomic service API: This API can be used in atomic services since API version 12.

ScrollEventType12+

Enumerates the scroll event types.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

NameValueDescription
SCROLL_START0The scroll event starts.
SCROLL_STOP1The scroll event ends.

RouterPageState

Enumerates the states of a page during routing.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

NameValueDescription
ABOUT_TO_APPEAR0The page is about to be displayed.
ABOUT_TO_DISAPPEAR1The page is about to be destroyed.
ON_PAGE_SHOW2The page is displayed.
ON_PAGE_HIDE3The page is hidden.
ON_BACK_PRESS4The page is returned.

TabContentState12+

Enumerates the states of the NavDestination component.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

NameValueDescription
ON_SHOW0The TabContent component is displayed.
ON_HIDE1The TabContent component is hidden.

NavDestinationInfo

Provides information about the NavDestination component.

System capability: SystemCapability.ArkUI.ArkUI.Full

NameTypeMandatoryDescription
navigationIdResourceStrYesID of the Navigation component that contains the target NavDestination component.
Atomic service API: This API can be used in atomic services since API version 12.
nameResourceStrYesName of the NavDestination component.
Atomic service API: This API can be used in atomic services since API version 12.
stateNavDestinationStateYesState of the NavDestination component.
Atomic service API: This API can be used in atomic services since API version 12.
index12+numberYesIndex of the NavDestination component in the navigation stack.
Atomic service API: This API can be used in atomic services since API version 12.
param12+ObjectNoParameters of the NavDestination component.
Atomic service API: This API can be used in atomic services since API version 12.
navDestinationId12+stringYesUnique ID of the NavDestination component.
Atomic service API: This API can be used in atomic services since API version 12.
mode15+NavDestinationModeNoMode of the NavDestination component.
Atomic service API: This API can be used in atomic services since API version 15.
uniqueId15+numberNoUnique ID of the NavDestination component.
Atomic service API: This API can be used in atomic services since API version 15.

NavigationInfo12+

Provides information about the Navigation component.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

NameTypeMandatoryDescription
navigationIdstringYesID of the Navigation component.
pathStackNavPathStackYesRouting stack of the Navigation component.

ScrollEventInfo12+

Provides the scroll event information.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

NameTypeMandatoryDescription
idstringYesID of the scrollable component.
uniqueIdnumberYesUnique ID of the scrollable component.
scrollEventScrollEventTypeYesType of the scroll event.
offsetnumberYesCurrent offset of the scrollable component.

ObserverOptions12+

Describes the observer options.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

NameTypeMandatoryDescription
idstringYesComponent ID.

RouterPageInfo

Provides the information about a page during routing.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

NameTypeMandatoryDescription
contextUIAbilityContext |UIContextYesContext of the router page that invokes the lifecycle callback.
indexnumberYesPosition of the router page that invokes the lifecycle callback, in the navigation stack.
namestringYesName of the page that invokes the lifecycle callback.
pathstringYesPath of the page that invokes the lifecycle callback.
stateRouterPageStateYesState of the router page that invokes the lifecycle callback.
pageId12+stringYesUnique ID of the router page that invokes the lifecycle callback.

DensityInfo12+

Provides the information contained in the callback when the screen pixel density changes.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

NameTypeMandatoryDescription
contextUIContextYesContext corresponding to the page when the screen pixel density changes.
densitynumberYesScreen pixel density after the change.
Value range: [0, +∞)

NavDestinationSwitchInfo12+

Provides the information about page switching of the Navigation component.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

NameTypeMandatoryDescription
contextUIAbilityContext |UIContextYesContext information corresponding to Navigation component that triggers page switching.
fromNavDestinationInfo |NavBarYesSource page for page switching.
toNavDestinationInfo |NavBarYesDestination page for page switching.
operationNavigationOperationYesPage switching operation type.

NavDestinationSwitchObserverOptions12+

Provides the observer options for the page switching event of the Navigation component.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

NameTypeMandatoryDescription
navigationIdResourceStrYesID of the target Navigation component.

TabContentInfo12+

Provides the TabContent switching information.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

NameTypeMandatoryDescription
tabContentIdstringYesID of the TabContent component.
tabContentUniqueIdnumberYesUnique ID of the TabContent component.
stateTabContentStateYesState of the TabContent component.
indexnumberYesIndex of the TabContent component. The index is zero-based.
idstringYesID of the Tabs component.
uniqueIdnumberYesUnique ID of the Tabs component.

uiObserver.on('navDestinationUpdate')

on(type: 'navDestinationUpdate', callback: Callback<NavDestinationInfo>): void

Subscribes to status changes of the NavDestination component.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is fixed at 'navDestinationUpdate', which indicates the status change event of the NavDestination component.
callbackCallback<NavDestinationInfo>YesCallback used to return the current state of the NavDestination component.

Example

// Index.ets
// Example usage of uiObserver.on('navDestinationUpdate', callback)
// uiObserver.off('navDestinationUpdate', callback)
import { uiObserver } 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() {
    uiObserver.on('navDestinationUpdate', (info) => {
      console.info('NavDestination state update', JSON.stringify(info));
    });
  }

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

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

uiObserver.off('navDestinationUpdate')

off(type: 'navDestinationUpdate', callback?: Callback<NavDestinationInfo>): void

Unsubscribes from status changes of the NavDestination component.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is fixed at 'navDestinationUpdate', which indicates the status change event of the NavDestination component.
callbackCallback<NavDestinationInfo>NoCallback used to return the current state of the NavDestination component.

Example

See the example for uiObserver.on('navDestinationUpdate').

uiObserver.on('navDestinationUpdate')

on(type: 'navDestinationUpdate', options: { navigationId: ResourceStr }, callback: Callback<NavDestinationInfo>): void

Subscribes to status changes of the NavDestination component.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is fixed at 'navDestinationUpdate', which indicates the status change event of the NavDestination component.
options{ navigationId: ResourceStr }YesID of the Navigation component that contains the target NavDestination component.
callbackCallback<NavDestinationInfo>YesCallback used to return the current state of the NavDestination component.

Example

// Index.ets
// Example usage of uiObserver.on('navDestinationUpdate', navigationId, callback)
// uiObserver.off('navDestinationUpdate', navigationId, callback)
import { uiObserver } 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() {
    uiObserver.on('navDestinationUpdate', { navigationId: "testId" }, (info) => {
      console.info('NavDestination state update', JSON.stringify(info));
    });
  }

  aboutToDisappear() {
    uiObserver.off('navDestinationUpdate', { navigationId: "testId" });
  }

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

uiObserver.off('navDestinationUpdate')

off(type: 'navDestinationUpdate', options: { navigationId: ResourceStr }, callback?: Callback<NavDestinationInfo>): void

Unsubscribes from status changes of the NavDestination component.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is fixed at 'navDestinationUpdate', which indicates the status change event of the NavDestination component.
options{ navigationId: ResourceStr }YesID of the Navigation component that contains the target NavDestination component.
callbackCallback<NavDestinationInfo>NoCallback used to return the current state of the NavDestination component.

Example

See the example for uiObserver.on('navDestinationUpdate').

uiObserver.on('scrollEvent')12+

on(type: 'scrollEvent', callback: Callback<ScrollEventInfo>): void

Subscribes to the start and end of a scroll event.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value 'scrollEvent' indicates the start and end of a scroll event.
callbackCallback<ScrollEventInfo>YesCallback used to return the Callback used to return the information about the scroll event.

Example

See the example for offscrollevent.

uiObserver.off('scrollEvent')12+

off(type: 'scrollEvent', callback?: Callback<ScrollEventInfo>): void

Unsubscribes from the start and end of a scroll event.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value 'scrollEvent' indicates the start and end of a scroll event.
callbackCallback<ScrollEventInfo>NoCallback used to return the Callback used to return the information about the scroll event.

Example

See the example for offscrollevent.

uiObserver.on('scrollEvent')12+

on(type: 'scrollEvent', options: ObserverOptions, callback: Callback<ScrollEventInfo>): void

Subscribes to the start and end of a scroll event.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value 'scrollEvent' indicates the start and end of a scroll event.
optionsObserverOptionsYesID of the target scrollable component.
callbackCallback<ScrollEventInfo>YesCallback used to return the Callback used to return the information about the scroll event.

Example

See the example for offscrollevent.

uiObserver.off('scrollEvent')12+

off(type: 'scrollEvent', options: ObserverOptions, callback?: Callback<ScrollEventInfo>): void

Unsubscribes from the start and end of a scroll event.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value 'scrollEvent' indicates the start and end of a scroll event.
optionsObserverOptionsYesID of the target scrollable component.
callbackCallback<ScrollEventInfo>NoCallback used to return the Callback used to return the information about the scroll event.

Example

import { uiObserver } from '@kit.ArkUI'

@Entry
@Component
struct Index {
  scroller: Scroller = new Scroller();
  options: uiObserver.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(() => {
            uiObserver.on('scrollEvent', (info) => {
              console.info('scrollEventInfo', JSON.stringify(info));
            });
          })
        Button('UIObserver off')
          .onClick(() => {
            uiObserver.off('scrollEvent');
          })
      }

      Row() {
        Button('UIObserverWithId on')
          .onClick(() => {
            uiObserver.on('scrollEvent', this.options, (info) => {
              console.info('scrollEventInfo', JSON.stringify(info));
            });
          })
        Button('UIObserverWithId off')
          .onClick(() => {
            uiObserver.off('scrollEvent', this.options);
          })
      }
    }
    .height('100%')
  }
}

uiObserver.on('routerPageUpdate')11+

on(type: 'routerPageUpdate', context: UIAbilityContext|UIContext, callback: Callback<RouterPageInfo>): void

Subscribes to state changes of the page during routing.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is fixed at 'routerPageUpdate', which indicates the state change event of the page during routing.
contextUIAbilityContext |UIContextYesContext information, which is used to specify the scope of the page to be listened for.
callbackCallback<RouterPageInfo>YesCallback used to return the If pageInfo is passed, the current page state is returned.

Example

// used in UIAbility
import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
import { UIContext, window, uiObserver } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  private uiContext: UIContext|null = null;

  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
    // Subscribe to the target events within the scope of the page under the ability context.
    uiObserver.on('routerPageUpdate', this.context, (info: uiObserver.RouterPageInfo) => {
      console.info('[uiObserver][abilityContext] got info: ' + JSON.stringify(info))
    })
  }

  onWindowStageCreate(windowStage: window.WindowStage): void {
    windowStage.loadContent('pages/Index', (err) => {
      windowStage.getMainWindow((err: BusinessError, data) => {
        let windowInfo: window.Window = data;
        // Obtain a UIContext instance.
        this.uiContext = windowInfo.getUIContext();
        // Subscribe to the target events within the scope of the page under the UI context.
        uiObserver.on('routerPageUpdate', this.uiContext, (info: uiObserver.RouterPageInfo)=>{
          console.info('[uiObserver][uiContext] got info: ' + JSON.stringify(info))
        })
      })
    });
  }

  // ... other function in EntryAbility
}

uiObserver.off('routerPageUpdate')11+

off(type: 'routerPageUpdate', context: UIAbilityContext|UIContext, callback?: Callback<RouterPageInfo>): void

Unsubscribes to state changes of the page during routing.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is fixed at 'routerPageUpdate', which indicates the state change event of the page during routing.
contextUIAbilityContext |UIContextYesContext information, which is used to specify the scope of the page to be listened for.
callbackCallback<RouterPageInfo>NoCallback to be unregistered.

Example

// used in UIAbility
import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
import { uiObserver, UIContext } from '@kit.ArkUI';

export default class EntryAbility extends UIAbility {
  // Before actual use, uiContext must be assigned a value. For details, see the example for uiObserver.on('routerPageUpdate').
  private uiContext: UIContext|null = null;

  onDestroy(): void {
    // Unregister all callbacks for the routerPageUpdate event under the current ability context.
    uiObserver.off('routerPageUpdate', this.context)
  }

  onWindowStageDestroy(): void {
    // Unregister all callbacks for the routerPageUpdate event under the UI context.
    if (this.uiContext) {
      uiObserver.off('routerPageUpdate', this.uiContext);
    }
  }

  // ... other function in EntryAbility
}

uiObserver.on('densityUpdate')12+

on(type: 'densityUpdate', context: UIContext, callback: Callback<DensityInfo>): void

Subscribes to the pixel density changes of the screen.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value 'densityUpdate' indicates the pixel density changes of the screen.
contextUIContextYesContext information, which is used to specify the scope of the page to be listened for.
callbackCallback<DensityInfo>YesCallback used to return the screen pixel density after the change.

Example

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

@Entry
@Component
struct Index {
  @State density: number = 0;
  @State message: string = 'Listener not registered'

  densityUpdateCallback = (info: uiObserver.DensityInfo) => {
    this.density = info.density;
    this.message = 'DPI after change:' + this.density.toString();
  }

  build() {
    Column() {
      Text(this.message)
        .fontSize(24)
        .fontWeight(FontWeight.Bold)
      Button ('Subscribe to Screen Pixel Density Changes')
        .onClick(() => {
          this.message = 'Listener registered'
          uiObserver.on('densityUpdate', this.getUIContext(), this.densityUpdateCallback);
        })
    }
  }
}

uiObserver.off('densityUpdate')12+

off(type: 'densityUpdate', context: UIContext, callback?: Callback<DensityInfo>): void

Unsubscribes from the pixel density changes of the screen.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value 'densityUpdate' indicates the pixel density changes of the screen.
contextUIContextYesContext information, which is used to specify the scope of the page to be listened for.
callbackCallback<DensityInfo>NoCallback to be unregistered. If this parameter is not specified, this API unregisters all callbacks for the densityUpdate event under the current UI context.
import { uiObserver, UIContext } from '@kit.ArkUI';

@Entry
@Component
struct Index {
  @State density: number = 0;
  @State message: string = 'Listener not registered'

  densityUpdateCallback = (info: uiObserver.DensityInfo) => {
    this.density = info.density;
    this.message = 'DPI after change:' + this.density.toString();
  }

  build() {
    Column() {
      Text(this.message)
        .fontSize(24)
        .fontWeight(FontWeight.Bold)
      Button ('Subscribe to Screen Pixel Density Changes')
        .margin({ bottom: 10 })
        .onClick(() => {
          this.message = 'Listener registered'
          uiObserver.on('densityUpdate', this.getUIContext(), this.densityUpdateCallback);
        })
      Button ('Unsubscribe from Screen Pixel Density Changes')
        .onClick(() => {
          this.message = 'Listener not registered'
          uiObserver.off('densityUpdate', this.getUIContext(), this.densityUpdateCallback);
        })
    }
  }
}

uiObserver.on('willDraw')12+

on(type: 'willDraw', context: UIContext, callback: Callback<void>): void

Subscribes to the dispatch of drawing instructions in each frame.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
typestringYesEvent event. The value 'willDraw' indicates whether drawing is about to occur.
contextUIContextYesContext information, which is used to specify the scope of the page to be listened for.
callbackCallback<void>YesCallback used to return the

Example

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

@Entry
@Component
struct Index {
  willDrawCallback = () => {
    console.info("willDraw instruction dispatched.")
  }
  build() {
    Column() {
      Button('Subscribe to Drawing Instruction Dispatch')
        .onClick(() => {
          uiObserver.on('willDraw', this.getUIContext(), this.willDrawCallback);
        })
    }
  }
}

uiObserver.off('willDraw')12+

off(type: 'willDraw', context: UIContext, callback?: Callback<void>): void

Unsubscribes from the dispatch of drawing instructions in each frame.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
typestringYesEvent event. The value 'willDraw' indicates whether drawing is about to occur.
contextUIContextYesContext information, which is used to specify the scope of the page to be listened for.
callbackCallback<void>NoCallback to be unregistered.
import { uiObserver } from '@kit.ArkUI';

@Entry
@Component
struct Index {
  willDrawCallback = () => {
    console.info("willDraw instruction dispatched.")
  }

  build() {
    Column() {
      Button('Subscribe to Drawing Instruction Dispatch')
        .margin({ bottom: 10 })
        .onClick(() => {
          uiObserver.on('willDraw', this.getUIContext(), this.willDrawCallback);
        })
      Button('Unsubscribe from Drawing Instruction Dispatch')
        .onClick(() => {
          uiObserver.off('willDraw', this.getUIContext(), this.willDrawCallback);
        })
    }
  }
}

uiObserver.on('didLayout')12+

on(type: 'didLayout', context: UIContext, callback: Callback<void>): void

Subscribes to layout completion status in each frame.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value 'didLayout' indicates whether the layout has been completed.
contextUIContextYesContext information, which is used to specify the scope of the page to be listened for.
callbackCallback<void>YesCallback used to return the

Example

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

@Entry
@Component
struct Index {
  didLayoutCallback = () => {
    console.info("Layout completed.");
  }
  build() {
    Column() {
      Button('Subscribe to Layout Completion')
        .onClick(() => {
          uiObserver.on('didLayout', this.getUIContext(), this.didLayoutCallback);
        })
    }
  }
}

uiObserver.off('didLayout')12+

off(type: 'didLayout', context: UIContext, callback?: Callback<void>): void

Unsubscribes from layout completion status in each frame.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value 'didLayout' indicates whether the layout has been completed.
contextUIContextYesContext information, which is used to specify the scope of the page to be listened for.
callbackCallback<void>NoCallback to be unregistered.
import { uiObserver } from '@kit.ArkUI';

@Entry
@Component
struct Index {
  didLayoutCallback = () => {
    console.info("Layout completed.");
  }

  build() {
    Column() {
      Button('Subscribe to Layout Completion')
        .margin({ bottom: 10 })
        .onClick(() => {
          uiObserver.on('didLayout', this.getUIContext(), this.didLayoutCallback);
        })
      Button ('Unsubscribe from Layout Completion')
        .onClick(() => {
          uiObserver.off('didLayout', this.getUIContext(), this.didLayoutCallback);
        })
    }
  }
}

uiObserver.on('navDestinationSwitch')12+

on(type: 'navDestinationSwitch', context: UIAbilityContext|UIContext, callback: Callback<NavDestinationSwitchInfo>): void

Subscribes to the page switching event of the Navigation component.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value 'navDestinationSwitch' indicates the page switching event of the Navigation component.
contextUIAbilityContext |UIContextYesContext information, which is used to specify the scope of the page switching event to be listened for.
callbackCallback<NavDestinationSwitchInfo>YesCallback used to return the information about the page switching event.

Example

// EntryAbility.ets
// Example usage of uiObserver.on('navDestinationSwitch', UIAbilityContext, callback)
// uiObserver.off('navDestinationSwitch', UIAbilityContext, callback)
import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
import { uiObserver, window } from '@kit.ArkUI';
import { hilog } from "@kit.PerformanceAnalysisKit"

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

export default class EntryAbility extends UIAbility {
  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
    uiObserver.on('navDestinationSwitch', this.context, callBackFunc);
  }

  onDestroy(): void {
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy');
    uiObserver.off('navDestinationSwitch', this.context, callBackFunc);
  }

  onWindowStageCreate(windowStage: window.WindowStage): void {
    // Main window is created, set main page for this ability
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');

    windowStage.loadContent('pages/Index', (err, data) => {
      if (err.code) {
        hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
        return;
      }
      hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
    });
  }

  onWindowStageDestroy(): void {
    // Main window is destroyed, release UI related resources
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');
  }

  onForeground(): void {
    // Ability has brought to foreground
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground');
  }

  onBackground(): void {
    // Ability has back to background
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground');
  }
}
// Index.ets
// Example usage of uiObserver.on('navDestinationSwitch', UIContext, callback)
// uiObserver.off('navDestinationSwitch', UIContext, callback)
import { uiObserver } from '@kit.ArkUI';

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

function callBackFunc(info: uiObserver.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() {
    uiObserver.on('navDestinationSwitch', this.getUIContext(), callBackFunc)
  }

  aboutToDisappear() {
    uiObserver.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%')
  }
}

uiObserver.off('navDestinationSwitch')12+

off(type: 'navDestinationSwitch', context: UIAbilityContext|UIContext, callback?: Callback<NavDestinationSwitchInfo>): void

Unsubscribes from the page switching event of the Navigation component.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value 'navDestinationSwitch' indicates the page switching event of the Navigation component.
contextUIAbilityContext |UIContextYesContext information, which is used to specify the scope of the page switching event to be listened for.
callbackCallback<NavDestinationSwitchInfo>NoCallback to be unregistered.

Example

See the example for uiObserver.on('navDestinationSwitch').

uiObserver.on('navDestinationSwitch')12+

on(type: 'navDestinationSwitch', context: UIAbilityContext|UIContext, observerOptions: NavDestinationSwitchObserverOptions, callback: Callback<NavDestinationSwitchInfo>): void

Subscribes to the page switching event of the Navigation component.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value 'navDestinationSwitch' indicates the page switching event of the Navigation component.
contextUIAbilityContext |UIContextYesContext information, which is used to specify the scope of the page switching event to be listened for.
observerOptionsNavDestinationSwitchObserverOptionsYesObserver options.
callbackCallback<NavDestinationSwitchInfo>YesCallback used to return the information about the page switching event.

Example

// EntryAbility.ets
// Example usage of uiObserver.on('navDestinationSwitch', UIAbilityContext, NavDestinationSwitchObserverOptions, callback)
// uiObserver.off('navDestinationSwitch', UIAbilityContext, NavDestinationSwitchObserverOptions, callback)
import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
import { uiObserver, window } from '@kit.ArkUI';
import { hilog } from "@kit.PerformanceAnalysisKit"

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

export default class EntryAbility extends UIAbility {
  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
    uiObserver.on('navDestinationSwitch', this.context, {
      navigationId: "myNavId"
    }, callBackFunc);
  }

  onDestroy(): void {
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy');
    uiObserver.off('navDestinationSwitch', this.context, {
      navigationId: "myNavId"
    }, callBackFunc);
  }

  onWindowStageCreate(windowStage: window.WindowStage): void {
    // Main window is created, set main page for this ability
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');

    windowStage.loadContent('pages/Index', (err, data) => {
      if (err.code) {
        hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
        return;
      }
      hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
    });
  }

  onWindowStageDestroy(): void {
    // Main window is destroyed, release UI related resources
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');
  }

  onForeground(): void {
    // Ability has brought to foreground
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground');
  }

  onBackground(): void {
    // Ability has back to background
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground');
  }
}
// Index.ets
// Example usage of uiObserver.on('navDestinationSwitch', UIContext, NavDestinationSwitchObserverOptions, callback)
// uiObserver.off('navDestinationSwitch', UIContext, NavDestinationSwitchObserverOptions, callback)
import { uiObserver } from '@kit.ArkUI';

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

function callBackFunc(info: uiObserver.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() {
    uiObserver.on('navDestinationSwitch', this.getUIContext(), { navigationId: "myNavId" }, callBackFunc)
  }

  aboutToDisappear() {
    uiObserver.off('navDestinationSwitch', this.getUIContext(), { navigationId: "myNavId" }, callBackFunc)
  }

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

uiObserver.off('navDestinationSwitch')12+

off(type: 'navDestinationSwitch', context: UIAbilityContext|UIContext, observerOptions: NavDestinationSwitchObserverOptions, callback?: Callback<NavDestinationSwitchInfo>): void

Unsubscribes from the page switching event of the Navigation component.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value 'navDestinationSwitch' indicates the page switching event of the Navigation component.
contextUIAbilityContext |UIContextYesContext information, which is used to specify the scope of the page switching event to be listened for.
observerOptionsNavDestinationSwitchObserverOptionsYesObserver options.
callbackCallback<NavDestinationSwitchInfo>NoCallback to be unregistered.

Example

See the example for uiObserver.on('navDestinationSwitch').

uiObserver.on('tabContentUpdate')12+

on(type: 'tabContentUpdate', callback: Callback<TabContentInfo>): void

Subscribes to the TabContent switching event.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value 'tabContentUpdate' indicates the TabContent switching event.
callbackCallback<TabContentInfo>YesCallback used to return the information about the TabContent switching event.

Example

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

function callbackFunc(info: uiObserver.TabContentInfo) {
  console.info('tabContentUpdate', JSON.stringify(info));
}

@Entry
@Component
struct TabsExample {

  aboutToAppear(): void {
    uiObserver.on('tabContentUpdate', callbackFunc);
  }

  aboutToDisappear(): void {
    uiObserver.off('tabContentUpdate', callbackFunc);
  }

  build() {
    Column() {
      Tabs() {
        TabContent() {
          Column().width('100%').height('100%').backgroundColor('#00CB87')
        }.tabBar('green').id('tabContentId0')

        TabContent() {
          Column().width('100%').height('100%').backgroundColor('#007DFF')
        }.tabBar('blue').id('tabContentId1')

        TabContent() {
          Column().width('100%').height('100%').backgroundColor('#FFBF00')
        }.tabBar('yellow').id('tabContentId2')

        TabContent() {
          Column().width('100%').height('100%').backgroundColor('#E67C92')
        }.tabBar('pink').id('tabContentId3')
      }
      .width(360)
      .height(296)
      .backgroundColor('#F1F3F5')
      .id('tabsId')
    }.width('100%')
  }
}

uiObserver.off('tabContentUpdate')12+

off(type: 'tabContentUpdate', callback?: Callback<TabContentInfo>): void

Unsubscribes from the TabContent switching event.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value 'tabContentUpdate' indicates the TabContent switching event.
callbackCallback<TabContentInfo>NoCallback to be unregistered.

Example

See the example for uiObserver.on('tabContentUpdate').

uiObserver.on('tabContentUpdate')12+

on(type: 'tabContentUpdate', options: ObserverOptions, callback: Callback<TabContentInfo>): void

Subscribes to the TabContent switching event.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value 'tabContentUpdate' indicates the TabContent switching event.
optionsObserverOptionsYesID of the target Tabs component.
callbackCallback<TabContentInfo>YesCallback used to return the information about the TabContent switching event.

Example

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

function callbackFunc(info: uiObserver.TabContentInfo) {
  console.info('tabContentUpdate', JSON.stringify(info));
}

@Entry
@Component
struct TabsExample {

  aboutToAppear(): void {
    uiObserver.on('tabContentUpdate', { id: 'tabsId' }, callbackFunc);
  }

  aboutToDisappear(): void {
    uiObserver.off('tabContentUpdate', { id: 'tabsId' }, callbackFunc);
  }

  build() {
    Column() {
      Tabs() {
        TabContent() {
          Column().width('100%').height('100%').backgroundColor('#00CB87')
        }.tabBar('green').id('tabContentId0')

        TabContent() {
          Column().width('100%').height('100%').backgroundColor('#007DFF')
        }.tabBar('blue').id('tabContentId1')

        TabContent() {
          Column().width('100%').height('100%').backgroundColor('#FFBF00')
        }.tabBar('yellow').id('tabContentId2')

        TabContent() {
          Column().width('100%').height('100%').backgroundColor('#E67C92')
        }.tabBar('pink').id('tabContentId3')
      }
      .width(360)
      .height(296)
      .backgroundColor('#F1F3F5')
      .id('tabsId')
    }.width('100%')
  }
}

uiObserver.off('tabContentUpdate')12+

off(type: 'tabContentUpdate', options: ObserverOptions, callback?: Callback<TabContentInfo>): void

Unsubscribes from the TabContent switching event.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value 'tabContentUpdate' indicates the TabContent switching event.
optionsObserverOptionsYesID of the target Tabs component.
callbackCallback<TabContentInfo>NoCallback to be unregistered.

Example

See the example for uiObserver.on('tabContentUpdate').

你可能感兴趣的鸿蒙文章

harmony 鸿蒙ArkUI

harmony 鸿蒙ARKUI_TextPickerCascadeRangeContent

harmony 鸿蒙ARKUI_TextPickerRangeContent

harmony 鸿蒙ArkUI_AnimateCompleteCallback

harmony 鸿蒙ArkUI_AttributeItem

harmony 鸿蒙ArkUI_ColorStop

harmony 鸿蒙ArkUI_ContextCallback

harmony 鸿蒙ArkUI_EventModule

harmony 鸿蒙ArkUI_ExpectedFrameRateRange

harmony 鸿蒙ArkUI_IntOffset

  • 所属分类: 后端技术
  • 本文标签: 软件 鸿蒙
  • 版权声明: 本文链接 https://seaxiang.com/blog/LxIFgk