HarmonyOS 鸿蒙Next中如何监听tab栏对应的页面的显示和消失

HarmonyOS 鸿蒙Next中如何监听tab栏对应的页面的显示和消失 如何监听tab栏对应的页面的显示和消失

4 回复

【解决方案】

方案一:通过onVisibleAreaChange监听Tab页的可见性变化,当完全不可见或完全可见时触发自定义PageShow/PageHide方法。
示例代码如下:

@Entry
@Component
struct TabsExample {
  @State selectedIndex: number = 2;
  @State currentIndex: number = 2;
  private controller: TabsController = new TabsController();
  @State demoList: Array<string> = ['首页', '发现', '推荐', '我的']

  @Builder
  tabBuilder(title: string, targetIndex: number) {
    Column() {
      Image(this.selectedIndex === targetIndex ? $r('app.media.background') : $r('app.media.startIcon'))
        .width(24)
        .height(24)
        .margin({ bottom: 4 })
        .objectFit(ImageFit.Contain)
      Text(title).fontColor(this.selectedIndex === targetIndex ? '#1698CE' : '#6B6B6B')
    }.width('100%')
    .height(50)
    .justifyContent(FlexAlign.Center)
  }

  // 自定义的show,可以自己随意命名
  PageShow(name: string) {
    console.info(`我是${name}触发的PageShow`)
  }

  // 自定义的hide,可以自己随意命名
  PageHide(name: string) {
    console.info(`我是${name}触发的PageHide`)
  }

  build() {
    Column() {
      Tabs({ barPosition: BarPosition.End, index: this.currentIndex, controller: this.controller }) {
        ForEach(this.demoList, (item: string, index: number) => {
          TabContent() {
            Column() {
              Text(`${item}内容`)
            }.width('100%').height('100%')
            .backgroundColor('#00CB87').justifyContent(FlexAlign.Center)
          }.tabBar(this.tabBuilder(item, index))
          .onVisibleAreaChange([0.0, 1.0], (isVisible: boolean, currentRatio: number) => {
            if (isVisible && currentRatio == 1.0) {
              // 调用自定义的show方法
              this.PageShow(item)
            } else if (currentRatio == 0.0) {
              // 调用自定义的hide方法
              this.PageHide(item)
            }
          })
        })
      }
    }
    .width('100%')
    .height('100%')
  }
}

方案二:利用onWillShow/onWillHide生命周期监听页面显示/隐藏事件,或者通过监听index修改来判断页面的切换。

@Entry
@Component
struct TabsExample11 {
  @State fontColor: string = '#182431'
  @State selectedFontColor: string = '#007DFF'
  @State currentIndex: number = 0
  private controller: TabsController = new TabsController()
  @State demoList: Array<string> = ['首页', '发现', '推荐', '我的']

  @Builder
  tabBuilder(index: number, name: string) {
    Column() {
      Text(name)
        .fontColor(this.currentIndex === index ? this.selectedFontColor : this.fontColor)
        .fontSize(16)
        .fontWeight(this.currentIndex === index ? 500 : 400)
        .lineHeight(22)
        .margin({ top: 17, bottom: 7 })
      Divider()
        .strokeWidth(2)
        .color('#007DFF')
        .opacity(this.currentIndex === index ? 1 : 0)
    }.width('100%')
  }

  build() {
    Column() {
      Tabs({ barPosition: BarPosition.Start, index: this.currentIndex, controller: this.controller }) {
        ForEach(this.demoList, (item: string, index: number) => {
          TabContent() {
            Column() {
              Text(`${item}内容`)
            }.width('100%').height('100%')
            .backgroundColor('#00CB87').justifyContent(FlexAlign.Center)
          }.tabBar(this.tabBuilder(index, item))
          .onWillShow(() => {
            console.info(`我是${item}进入触发`)
          })
          .onWillHide(() => {
            console.info(`我是${item}离开触发`)
          })
        })
      }
      .onTabBarClick((index: number) => {
        console.info('切换至', index + 1)
      })
      .onChange((index: number) => {
        this.currentIndex = index
      })
      .width(360)
      .height(296)
      .margin({ top: 52 })
      .backgroundColor('#F1F3F5')
    }.width('100%')
  }
}

更多关于HarmonyOS 鸿蒙Next中如何监听tab栏对应的页面的显示和消失的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


1. 使用 TabContent 组件的生命周期事件

TabContent 组件提供了 onWillShowonWillHide 事件,可直接监听当前 TabContent 页面的显示和隐藏:

  • onWillShow:TabContent 将要显示时触发(包括首次显示、切换、页面路由、窗口前后台切换)。
  • onWillHide:TabContent 将要隐藏时触发(包括切换、页面路由、窗口前后台切换)。

也可以参考 如何监听Tabs里面TabContent页面显示-方舟UI框架(ArkUI)-UI框架-应用框架开发

示例代码:

TabContent() {
  Column().width('100%').height('100%').backgroundColor('#00CB87')
}
.tabBar('green')
.id('tabContentId0')
.onWillShow(() => {
  console.info('TabContent 将要显示');
})
.onWillHide(() => {
  console.info('TabContent 将要隐藏');
});

2. 使用 Tabs 组件的 onChange 事件

通过 Tabs 的 onChange 事件监听页签切换,间接获取页面显示变化(返回当前显示页的索引):

Tabs()
  .onChange((index: number) => {
    console.info(`切换到第 ${index} 个页签`);
  });

3. 使用 uiObserver 监听 TabContent 切换事件

通过 uiObserver.on('tabContentUpdate') 全局监听所有 TabContent 页面的切换事件:

  • 无选项监听
import { uiObserver } from '@kit.ArkUI';

uiObserver.on('tabContentUpdate', (info: uiObserver.TabContentInfo) => {
  console.info('TabContent 切换信息:', JSON.stringify(info));
});
  • 指定 Tabs id 监听(推荐避免重复触发):
uiObserver.on('tabContentUpdate', { id: 'tabsId' }, (info: uiObserver.TabContentInfo) => {
  console.info('指定 Tabs 的 TabContent 切换:', JSON.stringify(info));
});

取消监听

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

4. 使用 UIObserver 类(通过 UIContext 获取)

在组件内通过 UIContext 获取 UIObserver 对象进行监听(适用于精细控制):

// 在组件生命周期中注册监听
aboutToAppear(): void {
  const observer = this.getUIContext().getUIObserver();
  observer.on('tabContentUpdate', (info: uiObserver.TabContentInfo) => {
    console.info('UIObserver 监听到 TabContent 切换:', JSON.stringify(info));
  });
}

aboutToDisappear(): void {
  const observer = this.getUIContext().getUIObserver();
  observer.off('tabContentUpdate', callbackFunc); // 取消监听
}

根据需求选择合适的方法:

  • 若需监听单个 TabContent 的显隐,直接使用 TabContent 的 onWillShow/onWillHide
  • 若需全局监听所有 TabContent 切换,使用 uiObserverUIObserver
  • 若只需知道页签切换索引,使用 Tabs 的 onChange

在HarmonyOS Next中,监听Tab栏对应页面的显示和消失可以使用TabContent组件的onAppearonDisappear事件。在TabContent中为每个页面分别设置这两个回调方法,当页面切换时自动触发相应事件。通过@State装饰器管理当前激活的Tab索引,结合TabContentonChange事件可获取页面切换状态。具体实现需在TabContent的每个子组件中定义onAppearonDisappear方法,系统会在页面显示或隐藏时执行对应逻辑。

在HarmonyOS Next中,可以通过TabContent组件的onAppearonDisAppear生命周期回调来监听对应页面的显示和消失事件。

具体实现示例:

TabContent() {
  Column() {
    Text('页面内容')
  }
  .onAppear(() => {
    console.log('页面显示')
    // 执行页面显示时的逻辑
  })
  .onDisAppear(() => {
    console.log('页面消失') 
    // 执行页面消失时的逻辑
  })
}

关键点说明:

  1. onAppear:当TabContent对应的页面显示时触发
  2. onDisAppear:当TabContent对应的页面从视图中消失时触发
  3. 这两个回调直接挂载在TabContent内的容器组件上

这种方法适用于需要根据页面可见性执行特定操作的场景,如数据加载、资源释放等。

回到顶部