HarmonyOS 如何让主界面切换到指定的嵌套的tab页面

app主界面里面有新闻、视频、等多个个栏目,用的是tab控件。每个栏目又有很多子栏目也是用的tab控件。那么怎么让主界面切换显示某个栏目的子栏目内容,相当于人工点击一下主栏目,再点击一下上面的子栏目按钮的效果。

HarmonyOS
1天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
FengTianYa

示例参考如下:

1、首页

//首页
import Tab1 from './Tab1'
import Tab2 from './Tab2'
import router from '@ohos.router'

let storage = LocalStorage.getShared()

Entry(storage)
Component

struct TabsExample1 {
  @State currentIndex: number = 0
  @LocalStorageProp('initTabIndex') initTabIndex: number = 0

  onPageShow(): void {
    this.currentIndex = this.initTabIndex
    const params = router.getParams() as Record<string, string>
    if (params) {
      this.currentIndex = Number.parseInt(params.tabIndex)
    }
  }

  @Builder
  tabBuilder(title: string, targetIndex: number) {
    Column() {
      Text(title)
        .fontColor(this.currentIndex === targetIndex ? '#1698CE' : '#6B6B6B')
    }
  }

  build() {
    Column() {
      Tabs({ barPosition: BarPosition.End, index: $$this.currentIndex }) {
        TabContent() {
          Tab1()
        }.tabBar(this.tabBuilder('tab1', 0))

        TabContent() {
          Tab2()
        }.tabBar(this.tabBuilder('tab2', 1))

      }
      .animationDuration(0)
      .backgroundColor('#F1F3F5')
      .onChange((index: number) => {
        this.currentIndex = index
      })
    }.width('100%')
  }
}

2、EntruAbility

// EntryAbility
import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { Router, window } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  funcAbilityWant: Want | undefined = undefined;
  uiContext: UIContext | undefined = undefined;

  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
    this.funcAbilityWant = want;
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
  }

  onWindowStageCreate(windowStage: window.WindowStage): void {
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
    let url = 'pages/Index';
    let storage: LocalStorage = new LocalStorage();
    storage.setOrCreate('initTabIndex', this.funcAbilityWant?.parameters?.tabIndex);
    storage.setOrCreate('initTab1Index', this.funcAbilityWant?.parameters?.tab1Index);
    storage.setOrCreate('initTab2Index', this.funcAbilityWant?.parameters?.tab2Index);
    // 冷启动, 通过storage传递参数
    windowStage.loadContent(url, storage, (err) => {
      if (err.code) {
        hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
        return;
      }
      let windowClass: window.Window;
      windowStage.getMainWindow((err, data) => {
        if (err.code) {
          return;
        }
        windowClass = data;
        this.uiContext = windowClass.getUIContext();
      });
      hilog.info(0x0000, 'testTag', 'Succeeded in loading the content.');

    });
  }

  // 热启动时会触发onNewWant, 通过router.param传递参数
  onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void {
    this.funcAbilityWant = want;
    let url = 'pages/Index';

    if (this.uiContext) {
      let router: Router = this.uiContext.getRouter();
      router.pushUrl({
        url: url,
        params: {
          tabIndex: this.funcAbilityWant?.parameters?.tabIndex,
          tab1Index: this.funcAbilityWant?.parameters?.tab1Index,
          tab2Index: this.funcAbilityWant?.parameters?.tab2Index
        }
      }).catch((err: BusinessError) => {
      });
    }
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
  }
}

3、Tab1

import { notificationManager } from '@kit.NotificationKit';
import { BusinessError } from '@kit.BasicServicesKit'
import { WantAgent, wantAgent } from '@kit.AbilityKit'
import { router } from '@kit.ArkUI';


@Component
export default struct Tab1 {
  @LocalStorageProp('initTab1Index') initIndex: number = 0
  @State currentIndex: number = 0
  private wantAgentObj: WantAgent = new Object();

  aboutToAppear(): void {
    this.currentIndex = this.initIndex
    const params = router.getParams() as Record<string, string>
    if (params?.tab1Index) {
      this.currentIndex = Number.parseInt(params.tab1Index)
    }
    this.createWantAgent().then(want => {
      this.wantAgentObj = want;
    }).catch((err: Error) => {
    });

  }

  @Builder
  tabBuilder(title: string, targetIndex: number) {
    Column() {
      Text(title)
        .fontColor(this.currentIndex === targetIndex ? '#1698CE' : '#6B6B6B')
    }
  }

  build() {
    Column() {
      Tabs({
        barPosition: BarPosition.Start,
        index: $$this.currentIndex
      }) {
        TabContent() {
          Column() {
            Text("tab1-1")
              .fontSize(30)
            Button("发送通知, 跳转到tab2-3")
              .onClick(() => {
                this.publishNotification()
              })
          }
        }.tabBar(this.tabBuilder('tab1-1', 0))

        TabContent() {
          Text("tab1-2")
            .fontSize(30)
        }.tabBar(this.tabBuilder('tab1-2', 1))

        TabContent() {
          Text("tab1-3")
            .fontSize(30)
        }.tabBar(this.tabBuilder('tab1-3', 2))
      }
      .onChange((index: number) => {
        this.currentIndex = index
      })
    }
  }

  publishNotification() {
    notificationManager.isNotificationEnabled().then((data: boolean) => {
      console.info("isNotificationEnabled success, data: " + JSON.stringify(data));
      if (!data) {
        notificationManager.requestEnableNotification().then(() => {
          console.info(`[ANS] requestEnableNotification success`);
        }).catch((err: BusinessError) => {
          if (1600004 == err.code) {
            console.info(`[ANS] requestEnableNotification refused`);
          } else {
            console.error(`[ANS] requestEnableNotification failed, code is ${err.code}, message is ${err.message}`);
          }
        });
      }
    }).catch((err: BusinessError) => {
      console.error(`isNotificationEnabled fail: ${JSON.stringify(err)}`);
    });

    let notificationRequest: notificationManager.NotificationRequest = {
      // 描述通知的请求
      id: 1, // 通知ID
      content: {
        // 通知内容
        notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, // 普通文本类型通知
        normal: {
          // 基本类型通知内容
          title: '跳转测试',
          text: '点击跳转到tab2-3'
        }
      },
      notificationSlotType: notificationManager.SlotType.SOCIAL_COMMUNICATION,
      wantAgent: this.wantAgentObj
    }
    notificationManager.publish(notificationRequest).then(() => { // 发布通知
      console.info('publish success');
    }).catch((err: Error) => {
      console.error(`publish failed,message is ${err}`);
    });
  }

  createWantAgent(): Promise<WantAgent> {
    let wantAgentInfo = {
      wants: [
        {
          deviceId: '', // deviceId为空表示本设备
          bundleName: 'com.example.myapplication',
          abilityName: 'EntryAbility',
          parameters: {
            tabIndex: 1, // 例如新闻tab的index为1
            tab2Index: 2   // 例如新闻tab中,政务tab的index为2
          }
        }
      ],
      operationType: wantAgent.OperationType.START_ABILITY,
      requestCode: 100,
    } as wantAgent.WantAgentInfo;
    return wantAgent.getWantAgent(wantAgentInfo);
  }
}

4、Tab2

import { router } from '@kit.ArkUI'

@Component
export default struct Tab2 {
  @LocalStorageProp('initTab2Index') initIndex: number = 0
  @State currentIndex: number = 0

  aboutToAppear(): void {
    this.currentIndex = this.initIndex
    const params = router.getParams() as Record<string, string>
    if (params?.tab2Index) {
      this.currentIndex = Number.parseInt(params.tab2Index)
    }
  }

  @Builder
  tabBuilder(title: string, targetIndex: number) {
    Column() {
      Text(title)
        .fontColor(this.currentIndex === targetIndex ? '#1698CE' : '#6B6B6B')
    }
  }

  build() {
    Column() {
      Tabs({
        barPosition: BarPosition.Start,
        index: $$this.currentIndex
      }) {
        TabContent() {
          Text("tab2-1")
            .fontSize(30)
        }.tabBar(this.tabBuilder('tab2-1', 0))

        TabContent() {
          Text("tab2-2")
            .fontSize(30)
        }.tabBar(this.tabBuilder('tab2-2', 1))

        TabContent() {
          Text("tab2-3")
            .fontSize(30)
        }.tabBar(this.tabBuilder('tab2-3', 2))
      }
      .onChange((index: number) => {
        this.currentIndex = index
      })

    }
  }
}
分享
微博
QQ
微信
回复
1天前
相关问题
如何拉起设置应用界面
1862浏览 • 1回复 待解决
如何拉起设置应用界面
492浏览 • 2回复 待解决
HarmonyOS 其他线程切换到主线程api
67浏览 • 1回复 待解决
HarmonyOS tab切换demo
15浏览 • 1回复 待解决
HarmonyOS 如何关闭指定页面
3浏览 • 1回复 待解决
app切换到后台时进度条处理问题
2609浏览 • 0回复 待解决
HarmonyOS Tab指定默认Index
23浏览 • 1回复 待解决
JS开发界面怎么更换?
5076浏览 • 1回复 待解决