HarmonyOS 鸿蒙Next 如何让主界面切换到指定的嵌套的tab页面
HarmonyOS 鸿蒙Next 如何让主界面切换到指定的嵌套的tab页面
可以参考下面样例代码进行实现。 主要逻辑为:
1,在消息推送的Want中传入tabIndex参数控制跳转的栏目
2,在EntryAbility中接收Want中的tanIndex参数,如果是冷启动则通过LocalStorage传参,热启动则通过router传参
3,在tab控件所在页面接收到参数后,通过@state进行状态控制
1,首页
typescript
//首页
import Tab1 from './Tab1'
import Tab2 from './Tab2'
import router from '@ohos.router'
let storage = LocalStorage.getShared()
Entry(storage)
Component
struct TabsExample1 {
[@State](/user/State) currentIndex: number = 0
[@LocalStorageProp](/user/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](/user/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
typescript
// EntryAbility
import { AbilityConstant, UIAbility, Want } from '[@kit](/user/kit).AbilityKit';
import { hilog } from '[@kit](/user/kit).PerformanceAnalysisKit';
import { Router, window } from '[@kit](/user/kit).ArkUI';
import { BusinessError } from '[@kit](/user/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
typescript
import { notificationManager } from '[@kit](/user/kit).NotificationKit';
import { BusinessError } from '[@kit](/user/kit).BasicServicesKit'
import { WantAgent, wantAgent } from '[@kit](/user/kit).AbilityKit'
import { router } from '[@kit](/user/kit).ArkUI';
[@Component](/user/Component)
export default struct Tab1{
[@LocalStorageProp](/user/LocalStorageProp)('initTab1Index') initIndex: number = 0
[@State](/user/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](/user/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
javascript
import { router } from ‘@kit.ArkUI’
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
})
}
}
}
更多关于HarmonyOS 鸿蒙Next 如何让主界面切换到指定的嵌套的tab页面的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS鸿蒙Next中,要让主界面切换到指定的嵌套Tab页面,可遵循以下步骤:
- 确保推送服务已开通:在鸿蒙后台AppGallery Connect中开通推送服务,并正确配置client_id。
- 处理推送消息:应用中接收并处理推送消息,根据消息内容确定要跳转的Tab。
- 使用Navigation进行页面导航:根据要跳转的Tab,设置相应的导航页面列表和页面栈信息,并调用pushPath或相关方法进行跳转。
- 配置Tabs组件:确保应用中已正确配置Tabs组件,并设置了相应的TabBar和TabContent。TabBar组件通常用于底部导航,每个Tab项对应一个不同的页面或视图。
- 嵌套Tab处理:如遇到Tab嵌套情况,可通过TabsController控制器来改变父Tab的标签index,从而达到控制子Tab滑动时一级Tab切换的效果。
通过以上步骤,可以实现HarmonyOS鸿蒙Next主界面切换到指定的嵌套Tab页面。如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html。