鸿蒙Navigation的页面跳转官方代码

星河版本

文章部分代码来源于官方

文章部分代码来源于官方只是自己改了容易理解

与API4不同的Navigation

新版本使用的思路是

1、创建页面栈

pageInfos: NavPathStack = new NavPathStack();

2、resources/base/profile创建 router_map.json 文件

{
  "routerMap": [
    {
      "name": "pageOne",
      "pageSourceFile": "src/main/ets/pages/Navigation/EntryPageOne.ets",
      "buildFunction": "PageOneBuilder",
      "data": {
        "description": "this is pageOne"
      }
    },
    {
      "name": "pageTwo",
      "pageSourceFile": "src/main/ets/pages/Navigation/EntryPageTwo.ets",
      "buildFunction": "PageTwoBuilder",
      "data": {
        "description": "this is pageTwo"
      }
    }
  ]
}

3、将配置文件载入module.json5

{
  "module": {
    "name": "entry",
    "type": "entry",
    "description": "$string:module_desc",
    "mainElement": "EntryAbility",
    "deviceTypes": [
      "phone",
      "tablet",
      "2in1"
    ],
    "deliveryWithInstall": true,
    "installationFree": false,
    "pages": "$profile:main_pages",
    "routerMap": "$profile:router_map",
    "abilities": [
      {
        "name": "EntryAbility",
        "srcEntry": "./ets/entryability/EntryAbility.ets",
        "description": "$string:EntryAbility_desc",
        "icon": "$media:layered_image",
        "label": "$string:EntryAbility_label",
        "startWindowIcon": "$media:startIcon",
        "startWindowBackground": "$color:start_window_background",
        "exported": true,
        "skills": [
          {
            "entities": [
              "entity.system.home"
            ],
            "actions": [
              "action.system.home"
            ]
          }
        ]
      }
    ],
    "extensionAbilities": [
      {
        "name": "EntryBackupAbility",
        "srcEntry": "./ets/entrybackupability/EntryBackupAbility.ets",
        "type": "backup",
        "exported": false,
        "metadata": [
          {
            "name": "ohos.extension.backup",
            "resource": "$profile:backup_config"
          }
        ],
      }
    ]
  }
}

加入 "routerMap": "$profile:router_map"

$的用法之一读取本地resources/base下目录,另一个用于响应式变量

4、创建页面

NavigationExample.ets

/*
* Copyright (C) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

@Entry
@Component
@Preview
struct NavigationExample {
  pageInfos: NavPathStack = new NavPathStack();

  build() {
    Navigation(this.pageInfos) {

      Column({ space: 12 }) {
        Text("首页")
          .fontSize("15")
          .width("100%")
          .height('20vp')
          .fontColor(Color.Black)
        Button("芜湖芜湖")       .width("100%")
          .height('20vp')

        Button('第一个页面', { stateEffect: true, type: ButtonType.Capsule })
          .width("100%")
          .height('20vp')
          .onClick(() => {
            //Push the NavDestination page information specified by name onto the stack, and pass the data as param.
            this.pageInfos.pushPathByName('pageOne', null);
          })
        Button('第二个页面', { stateEffect: true, type: ButtonType.Capsule })
          .width("100%")
          .height('20vp')
          .onClick(() => {
            //Push the NavDestination page information specified by name onto the stack, and pass the data as param.
            this.pageInfos.pushPathByName('pageTwo', null);
          })

      }
      .width($r('app.string.navDestination_width'))
      .height($r('app.string.navDestination_height'))
      .justifyContent(FlexAlign.End)
      .padding({
        bottom: $r('app.string.column_padding'),
        left: $r('app.string.column_padding'),
        right: $r('app.string.column_padding')
      })
    }
    .title($r('app.string.entry_index_title'))
  }
}

EntryPageOne.ets

/*
* Copyright (C) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import Logger from '../../common/utils/Logger';

@Builder
export function PageOneBuilder(name: string, param: Object) {
  PageOne()
}

const COLUMN_SPACE: number = 12;

@Component
export struct PageOne {
  pageInfos: NavPathStack = new NavPathStack();

  build() {
    NavDestination() {
      Column({ space: 10 }) {
        Text("第一个页面")
          .fontSize("15")
          .width("100%")
          .height('20vp')
          .fontColor(Color.Black)
        Button('返回首页', { stateEffect: true, type: ButtonType.Capsule })
          .width("100%")
          .height('20vp')
          .onClick(() => {
            //Clear all pages in the stack.
            this.pageInfos.clear();
          })
        Button('第二个页面', { stateEffect: true, type: ButtonType.Capsule })
          .width("100%")
          .height('20vp')
          .onClick(() => {
            //Push the NavDestination page information specified by name onto the stack, and pass the data as param.
            this.pageInfos.pushPathByName('pageTwo', null);
          })
        Button("第一个页面", { stateEffect: true, type: ButtonType.Capsule })
          .width("100%")
          .height('20vp')
          .onClick(() => {
            //Push the NavDestination page information specified by name onto the stack, and pass the data as param.
            this.pageInfos.pushPathByName('pageOne', null);
          })

      }
      .width($r('app.string.navDestination_width'))
      .height($r('app.string.navDestination_height'))
      .justifyContent(FlexAlign.End)
      .padding({
        bottom: $r('app.string.column_padding'),
        left: $r('app.string.column_padding'),
        right: $r('app.string.column_padding')
      })
    }
    .title('entry-pageOne')
    .onReady((context: NavDestinationContext) => {
      this.pageInfos = context.pathStack;
      Logger.info("current page config info is " + JSON.stringify(context.getConfigInRouteMap()));
    })
  }
}

EntryPageTwo.ets

/*
* Copyright (C) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import Logger from '../../common/utils/Logger';

@Builder
export function PageTwoBuilder(name: string, param: Object) {
  PageTwo()
}

const COLUMN_SPACE: number = 12;

@Component
export struct PageTwo {
  pageInfos: NavPathStack = new NavPathStack();

  build() {
    NavDestination() {

      Column({ space: 10 }) {
        Text("第2个页面")
          .fontSize("15")
          .width("100%")
          .height('20vp')
          .fontColor(Color.Black)

        Button("返回首页", { stateEffect: true, type: ButtonType.Capsule })
          .width("100%")
          .height('20vp')
          .onClick(() => {
            this.pageInfos.clear(); //Clear all pages in the stack
          })
        Button("第一个页面", { stateEffect: true, type: ButtonType.Capsule })
          .width("100%")
          .height('20vp')
          .onClick(() => {
            //Push the NavDestination page information specified by name onto the stack, and pass the data as param.
            this.pageInfos.pushPathByName('pageOne', null);
          })

        Button("第二个页面", { stateEffect: true, type: ButtonType.Capsule })
          .width("100%")
          .height('20vp')
          .onClick(() => {
            //Push the NavDestination page information specified by name onto the stack, and pass the data as param.
            this.pageInfos.pushPathByName('pageTwo', null);
          })
      }
      .width($r('app.string.navDestination_width'))
      .height($r('app.string.navDestination_height'))
      .justifyContent(FlexAlign.End)
      .padding({
        bottom: $r('app.string.column_padding'),
        left: $r('app.string.column_padding'),
        right: $r('app.string.column_padding')
      })
    }
    .title('entry-pageTwo')
    .onReady((context: NavDestinationContext) => {
      this.pageInfos = context.pathStack
      Logger.info('current page config info is ' + JSON.stringify(context.getConfigInRouteMap()));
    })
  }
}

string.json

{
  "string": [
    {
      "name": "module_desc",
      "value": "module description"
    },
    {
      "name": "EntryAbility_desc",
      "value": "description"
    },
    {
      "name": "EntryAbility_label",
      "value": "Navigation systemRouting"
    },
    {
      "name": "navDestination_width",
      "value": "100%"
    },
    {
      "name": "navDestination_height",
      "value": "100%"
    },
    {
      "name": "button_width",
      "value": "100%"
    },
    {
      "name": "button_height",
      "value": "40"
    },
    {
      "name": "column_padding",
      "value": "16"
    },
    {
      "name": "entry_index_title",
      "value": "NavIndex"
    },
    {
      "name": "entry_index",
      "value": "toIndex"
    },
    {
      "name": "entry_pageOne",
      "value": "toEntryPageOne"
    },
    {
      "name": "entry_pageTwo",
      "value": "toEntryPageTwo"
    },
    {
      "name": "harA_pageOne",
      "value": "toHarAPageOne"
    },
    {
      "name": "harA_pageTwo",
      "value": "toHarAPageTwo"
    },
    {
      "name": "harB_pageOne",
      "value": "toHarBPageOne"
    },
    {
      "name": "harB_pageTwo",
      "value": "toHarBPageTwo"
    },
    {
      "name": "hspA_pageOne",
      "value": "toHspAPageOne"
    },
    {
      "name": "hspA_pageTwo",
      "value": "toHspAPageTwo"
    },
    {
      "name": "hspB_pageOne",
      "value": "toHspBPageOne"
    },
    {
      "name": "hspB_pageTwo",
      "value": "toHspBPageTwo"
    }
  ]
}

5、修改 EntryAbility.ets

windowStage.loadContent('pages/Navigation/NavigationExample', (err) => {
    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.');
  });
}

这里换成自己的就好了pages/Navigation/NavigationExample

演示

screenshots

注意

按照官方的规范是需要创建router_map.json并且将配置文件负载到module.json5里面的,每一个组建页面都需要实现一个

@Builder
export function PageOneBuilder(name: string, param: Object) {
  PageOne()
}

创建自己的函数在router_map.json中配置buildFunction

{
  "name": "pageOne",
  "pageSourceFile": "src/main/ets/pages/Navigation/EntryPageOne.ets",
  "buildFunction": "PageOneBuilder",
  "data": {
    "description": "this is pageOne"
  }
}
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
下面是一个简单的示例代码,展示如何使用tkinter创建一个带有按钮的窗口,点击按钮后跳转到另一个页面: ```python import tkinter as tk class PageOne(tk.Frame): def __init__(self, master): tk.Frame.__init__(self, master) tk.Label(self, text="This is Page One").pack() tk.Button(self, text="Go to Page Two", command=lambda: master.switch_frame(PageTwo)).pack() class PageTwo(tk.Frame): def __init__(self, master): tk.Frame.__init__(self, master) tk.Label(self, text="This is Page Two").pack() tk.Button(self, text="Go to Page One", command=lambda: master.switch_frame(PageOne)).pack() class MainApplication(tk.Tk): def __init__(self): tk.Tk.__init__(self) self.title("Page Navigation") self.geometry("300x200") container = tk.Frame(self) container.pack(side="top", fill="both", expand=True) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) self.frames = {} for F in (PageOne, PageTwo): frame = F(container) self.frames[F] = frame frame.grid(row=0, column=0, sticky="nsew") self.switch_frame(PageOne) def switch_frame(self, frame_class): frame = self.frames[frame_class] frame.tkraise() if __name__ == "__main__": app = MainApplication() app.mainloop() ``` 在这个例子中,我们创建了三个类,分别代表了主应用程序(MainApplication)和两个页面(PageOne和PageTwo)。在主应用程序中,我们定义了一个switch_frame方法,用于切换页面。我们在构造函数中创建了PageOne和PageTwo的实例,并将它们存储在一个字典中。当我们调用switch_frame方法时,我们只需要传入要切换到的页面类即可。在每个页面类中,我们定义了一个按钮,用于在点击时切换到另一个页面。每个页面类都继承自tk.Frame,因此我们可以使用pack或grid等方法来布局页面中的其他组件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

艾米莉亚小汉堡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值