自学内容网 自学内容网

鸿蒙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"
  }
}

原文地址:https://blog.csdn.net/qq_18827959/article/details/140351326

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!