元行者:基于 ArkUI 生态的布局可视化交互演示项目

OpenHarmony 6.0 适配攻坚 —— 从 API9 到 API20 的应用升级实践

Branch1Tags0

ArkUI 布局指挥官:用七个小兵玩转四大布局(ArkTS)

项目简介

  • 本项目是对官方 ArkUI 布局容器示例的深度定制化开发。通过将抽象的布局属性(Flex, Column, Row)转化为具象的“军队点兵”场景,实现了一个可视化、交互式的排阵模拟工具。
  • 开发者通过点击底部的“点兵指令”,可以实时观察 7 名小兵在操场环境下的阵型变换。

演示效果

相关概念

  • 主轴:在布局容器中,默认存在两根轴,分别是主轴和交叉轴,不同的容器中主轴的方向不一样的。
    • 在Column容器中主轴的方向是垂直方向。
    • 在Row容器中主轴的方向是水平方向。
    • 在Flex容器中可以通过direction参数设置主轴的方向,设置为Column时,主轴的方向是垂直方向。设置为Row时,主轴的方向是水平方向。
    • 在Stack容器中没有明确主轴与交叉轴,通过设置alignContent参数来改变容器内组件的对齐方式。
  • 交叉轴:与主轴垂直相交的轴线,如果主轴是垂直方向,则交叉轴就是水平方向;如果主轴是水平方向,则交叉轴是垂直方向。

视觉演示

  • Flex 模式:模拟多兵种混合集结
  • Column 模式:模拟纵队排阵
  • Row 模式:模拟横向方阵

环境搭建

软件要求

    * [DevEco Studio](https://gitcode.com/openharmony/docs/blob/master/zh-cn/application-dev/quick-start/start-overview.md#%E5%B7%A5%E5%85%B7%E5%87%86%E5%A4%87)版本:DevEco Studio 6.0 Release

    OpenHarmony SDK版本:API version 20

硬件要求

    开发板类型:[润和RK3568开发板](https://gitcode.com/openharmony/docs/blob/master/zh-cn/device-dev/quick-start/quickstart-appendix-rk3568.md)
    OpenHarmony系统:6.1 Release

环境搭建

     1.搭建烧录环境
        https://ci.openharmony.cn/workbench/cicd/dailybuild/dailylist下载DAYU200的镜像源

        a. 导入镜像源配置。注意:需要更换镜像实际的路径位置

        b. 按住VOL-/RECOVERY 按键(图中标注的①号键)不松开 1.5秒时按一次RESET 按钮(图中标注的②号键)。此时烧录工具显示“发现一个LOADER设备” ,说明进入了烧写模式 松开按键,点击“执行”按钮进行烧录 如果烧写成功, 在工具界面右侧会显示下载完成

    2. 搭建开发环境
        a. 开始前请参考[工具准备](https://gitcode.com/openharmony/docs/blob/master/zh-cn/application-dev/quick-start/start-overview.md#%E5%B7%A5%E5%85%B7%E5%87%86%E5%A4%87),完成DevEco Studio的安装和开发环境配置。
        b. 开发环境配置完成后,请参考[使用工程向导](https://gitcode.com/openharmony/docs/blob/master/zh-cn/application-dev/quick-start/start-with-ets-stage.md#%E5%88%9B%E5%BB%BAets%E5%B7%A5%E7%A8%8B)创建工程(模板选择“Empty Ability”)。
        c. 工程创建完成后,选择使用[真机进行调测](https://gitcode.com/openharmony/docs/blob/master/zh-cn/application-dev/quick-start/start-with-ets-stage.md#%E4%BD%BF%E7%94%A8%E7%9C%9F%E6%9C%BA%E8%BF%90%E8%A1%8C%E5%BA%94%E7%94%A8)。

代码结构解读

- 本篇Codelab只对核心代码进行讲解,完整代码可以直接从gitcode获取。
├──entry/src/main/ets                        // 代码区
│  ├──common
│  │  └──constants
│  │     └──CommonConstants.ets                // 样式常量类
│  ├──entryability
│  │  └──EntryAbility.ts                // 程序入口类
│  ├──pages
│  │  ├──LayoutAlignIndex.ets           // 主界面
│  │  └──Second.ets                     // 视频播放界面                
│  ├──view
│  │  ├──ColumnAxisAlignRadioList.ets   // 自定义Column容器设置交叉轴对其方式属性
│  │  ├──ColumnMainAlignRadioList.ets   // 自定义Column容器设置主轴对其方式属性
│  │  ├──ColumnShowList.ets             // 自定义Column容器子元素列表文件
│  │  ├──CommonComponent.ets            // 自定义公共组件文件
│  │  ├──FlexAxisAlignRadioList.ets     // 自定义Flex容器设置交叉轴对其方式属性
│  │  ├──FlexMainAlignRadioList.ets     // 自定义Flex容器设置主轴对其方式属性
│  │  ├──FlexMainDirectionRadioList.ets // 自定义Flex容器设置主轴方向对其方式属性
│  │  ├──FlexShowList.ets               // 自定义Flex容器子元素列表文件
│  │  ├──RowAxisAlignRadioList.ets      // 自定义Row容器设置交叉轴对其方式属性
│  │  ├──RowMainAlignRadioList.ets      // 自定义Row容器设置主轴对其方式属性
│  │  ├──RowShowList.ets                // 自定义Row容器子元素列表文件
│  │  ├──StackAlignRadioList.ets        // 自定义Stack容器设置对其方式属性
│  │  └──StackComponent.ets             // 自定义Stack容器子元素文件
│  └──viewmodel
│     ├──AttributeModuleData.ets        // 属性模块数据
│     ├──ContainerModuleItem.ets        // 属性模块对象
│     ├──IndexData.ets                  // 首页数据
│     └──IndexListItem.ets              // 首页数据对象
└──entry/src/main/resource              // 应用静态资源目录

版本适配

基本配置

1. 使用DevEco打开SimpleCalculator工程
    a. 打开构建的项目

b. 使用Migrate Assistant自动迁移

c. 换build json5的配置
    i.D:\DEVfile\7788\kelong\layout\maker_layout\entry\build-profile.json5

    ii. D:\DEVfile\7788\kelong\layout\maker_layout\build-profile.json5

d. 同步工程、编译工程

e. 为应用配置签名信息,等待完成即可

新接口替换旧接口

1. D:\DEVfile\7788\kelong\layout\maker_layout\entry\src\main\ets\entryability\EntryAbility.ts路径下

    替换为
import { hilog } from "@kit.PerformanceAnalysisKit";
import { UIAbility } from "@kit.AbilityKit";
import { window } from "@kit.ArkUI";
    其他需要改动的地方

2. D:\DEVfile\7788\kelong\layout\maker_layout\entry\src\main\ets\pages\LayoutAlignIndex.ets路径下

    替换为
import { router } from '@kit.ArkUI';
3. D:\DEVfile\7788\kelong\layout\maker_layout\entry\src\main\ets\pages\Second.ets路径下

    替换为
import { router } from '@kit.ArkUI';

构建主页面

- 我们将完成示例主界面的设计,主界面由标题和4个容器模块的 List 组成,效果图如下:

1. 在ets目录下,新建几个子目录,点击鼠标右键 >New>Directory,新建名为view的自定义子组件目录、common公共目录和viewmodel数据目录。

2. 在LayoutAlignIndex.ets主界面中包含显示四种容器对齐方式的入口。
// LayoutAlignIndex.ets
/*
 * Copyright (c) 2022 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 router from '@ohos.router';
import { IndexListItem } from '../viewmodel/IndexListItem';
import {
  TITLE_FONT_WEIGHT,
  MARGIN_FONT_SIZE_SPACE,
  EIGHT_POINT_TWO_PERCENT,
  COMMON_FONT_WEIGHT,
  INDEX_COMPONENT_WITH_PERCENT,
  SECOND_PAGE,
  ALL_PERCENT
} from '../common/Constants/CommonConstants';
import { getIndexList } from '../viewmodel/IndexData';
import { router } from '@kit.ArkUI';

/**
 *index page
 */
@Entry
@Component
struct LayoutAlignIndex {
  private indexList: IndexListItem[] = getIndexList();

  build() {
    Column() {
      Text($r('app.string.index_title'))
        .width(ALL_PERCENT)
        .fontSize(MARGIN_FONT_SIZE_SPACE.SEVENTH_MARGIN)
        .fontWeight(TITLE_FONT_WEIGHT)
        .textAlign(TextAlign.Center)
        .fontColor(Color.Black)
        .margin({ top: EIGHT_POINT_TWO_PERCENT })
      List() {
        ForEach(this.indexList, (item: IndexListItem) => {
          ListItem() {
            ListItemComp({ item: item })
              .margin({ top: MARGIN_FONT_SIZE_SPACE.SECOND_MARGIN })
          }
        }, (item: IndexListItem) => JSON.stringify(item))
      }
      .height(ALL_PERCENT)
      .width(ALL_PERCENT)
      .listDirection(Axis.Vertical)
      .margin({ top: MARGIN_FONT_SIZE_SPACE.EIGHTH_MARGIN })
    }
    .backgroundColor($r('app.color.index_backgroundColor'))
    .justifyContent(FlexAlign.Start)
    .alignItems(HorizontalAlign.Start)
    .width(ALL_PERCENT)
    .height(ALL_PERCENT)
  }
}

@Component
struct ListItemComp {
  private item: IndexListItem = new IndexListItem();

  build() {
    Row() {
      Image(this.item.icon)
        .height(MARGIN_FONT_SIZE_SPACE.SEVENTH_MARGIN)
        .width(MARGIN_FONT_SIZE_SPACE.SEVENTH_MARGIN)
        .margin({
          left: MARGIN_FONT_SIZE_SPACE.SEVENTH_MARGIN,
          top: MARGIN_FONT_SIZE_SPACE.SIXTH_MARGIN,
          bottom: MARGIN_FONT_SIZE_SPACE.SIXTH_MARGIN
        })
      Text(this.item.name)
        .fontSize(MARGIN_FONT_SIZE_SPACE.FIFTH_MARGIN)
        .fontColor(Color.Black)
        .fontWeight(COMMON_FONT_WEIGHT)
        .textAlign(TextAlign.Center)
        .margin({ left: MARGIN_FONT_SIZE_SPACE.FIFTH_MARGIN })
    }
    .width(INDEX_COMPONENT_WITH_PERCENT)
    .height(EIGHT_POINT_TWO_PERCENT)
    .borderRadius(MARGIN_FONT_SIZE_SPACE.SEVENTH_MARGIN)
    .margin({ left: MARGIN_FONT_SIZE_SPACE.SECOND_MARGIN, right: MARGIN_FONT_SIZE_SPACE.SECOND_MARGIN })
    .backgroundColor($r("app.color.white"))
    .onClick(() => {
      router.pushUrl({
        url: SECOND_PAGE,
        params: {
          containerType: this.item.containerType,
          componentName: this.item.name,
          moduleList: this.item.moduleList
        }
      });
    })
  }
}

构建不同容器对齐方式显示界面

1. 在pages目录下,点击鼠标右键 >New>Page,新建Second.ets页面。在view目录下,点击鼠标右键 >New>ArkTS File,新建五个ArkTS文件,分别为ColumnShowList.ets、FlexShowList.ets、RowShowList.ets、StackComponent.ets和CommonComponent.ets。

2. 在ColumnShowList.ets中,自定组件ColumnShowList主要效果是在Column布局容器中,设置不同的主轴与交叉轴的对齐方式属性时,显示容器内元素的对齐方式,以及主轴对其方式和交叉轴对其方式属性设置模块。

    具体代码如下
// ColumnShowList.ets
/*
 * Copyright (c) 2022 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 { CommonItem } from './CommonComponent';
import {
  MARGIN_FONT_SIZE_SPACE,
  LIST,
  SHOW_LIST_HEIGHT_PERCENT,
  ALL_PERCENT
} from '../common/Constants/CommonConstants';
import { ColumnAxisAlignRadioList } from './ColumnAxisAlignRadioList';
import { ColumnMainAlignRadioList } from './ColumnMainAlignRadioList';

/**
 *Show List in Column
 */
@Component
export struct ColumnShowList {
  @Consume currentColumnJustifyContent: FlexAlign;
  @Consume currentColumnAlignItems: HorizontalAlign;

  build() {
    Column() {
      Column() {
        ForEach(LIST, (item: number) => {
          CommonItem({ item: item })
        }, (item: number) => JSON.stringify(item))
      }
      .alignItems(this.currentColumnAlignItems)
      .justifyContent(this.currentColumnJustifyContent)
      .padding(MARGIN_FONT_SIZE_SPACE.COMMON_PADDING)
      .width(ALL_PERCENT)
      .height(SHOW_LIST_HEIGHT_PERCENT.COLUMN_ROW_SHOW_LIST_HEIGHT)
      .backgroundImage($r('app.media.img'))
      .backgroundImageSize(ImageSize.Cover)
      .backgroundImagePosition(Alignment.Center)
      .margin({ top: MARGIN_FONT_SIZE_SPACE.EIGHTH_MARGIN })

      // set main align
      ColumnMainAlignRadioList()
        .margin({ top: MARGIN_FONT_SIZE_SPACE.EIGHTH_MARGIN })
      // set axis align
      ColumnAxisAlignRadioList()
        .margin({ top: MARGIN_FONT_SIZE_SPACE.EIGHTH_MARGIN })
    }
    .layoutWeight(1)
    .height(ALL_PERCENT)
    .width(ALL_PERCENT)
  }
}
3. 其中ColumnMainAlignRadioList子组件和ColumnAxisAlignRadioList子组件分别是设置主轴对齐方式单选框列表和设置交叉轴对齐方式单选框列表,并且在FlexShowList,RowShowList和StackComponent中都存在代码结构类似的子组件,只是设置的属性和参数单选框列表不同,后面不在重复其详细代码,这里选择其中一个单选框列表子组件来显示。
4. 在RowShowList.ets中,自定组件RowShowList主要效果是在Row布局容器中,当设置不同的主轴与交叉轴的对齐方式属性时,显示容器内元素的对齐方式。

    代码如下:
/*
 * Copyright (c) 2022 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 { CommonItem } from './CommonComponent';
import {
  MARGIN_FONT_SIZE_SPACE,
  LIST,
  SHOW_LIST_HEIGHT_PERCENT,
  ALL_PERCENT
} from '../common/Constants/CommonConstants';
import { RowAxisAlignRadioList } from './RowAxisAlignRadioList';
import { RowMainAlignRadioList } from './RowMainAlignRadioList';

/**
 *Show List in Row
 */
@Component
export struct RowShowList {
  @Consume currentRowJustifyContent: FlexAlign;
  @Consume currentRowAlignItems: VerticalAlign;

  build() {
    Column() {
      Row() {
        ForEach(LIST, (item: number) => {
          CommonItem({ item: item })
        }, (item: number) => JSON.stringify(item))
      }
      .alignItems(this.currentRowAlignItems)
      .justifyContent(this.currentRowJustifyContent)
      .padding(MARGIN_FONT_SIZE_SPACE.COMMON_PADDING)
      .width(ALL_PERCENT)
      .height(SHOW_LIST_HEIGHT_PERCENT.COLUMN_ROW_SHOW_LIST_HEIGHT)
      .backgroundImage($r('app.media.img'))
      .backgroundImageSize(ImageSize.Cover)
      .backgroundImagePosition(Alignment.Center)
      .margin({ top: MARGIN_FONT_SIZE_SPACE.EIGHTH_MARGIN })

      // set main align
      RowMainAlignRadioList()
        .margin({ top: MARGIN_FONT_SIZE_SPACE.EIGHTH_MARGIN })
      // set axis align
      RowAxisAlignRadioList()
        .margin({ top: MARGIN_FONT_SIZE_SPACE.EIGHTH_MARGIN })
    }
    .layoutWeight(1)
    .height(ALL_PERCENT)
    .width(ALL_PERCENT)
  }
}
5. 在StackComponent.ets中,自定组件StackComponent主要效果是在Stack布局容器中,设置不同对齐方式属性时,容器内堆叠元素的对齐方式。

    代码如下
/*
 * Copyright (c) 2022 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 { MARGIN_FONT_SIZE_SPACE, SHOW_LIST_HEIGHT_PERCENT,ALL_PERCENT } from '../common/Constants/CommonConstants';
import { StackAlignRadioList } from './StackAlignRadioList';

/**
 *Show child component  in Stack
 */
@Component
export struct StackComponent {
  @Consume currentStackAlignContent: Alignment;
  @Consume message: string;
  @State textAl: TextAlign = TextAlign.Center;

  build() {
    Column() {
      Stack({ alignContent: this.currentStackAlignContent }) {
        Text('')
          .width(ALL_PERCENT)
          .height(ALL_PERCENT)
          .fontSize(MARGIN_FONT_SIZE_SPACE.FOURTH_MARGIN)
          .backgroundColor($r('app.color.show_list_backgroundColor'))
        Text(this.message)
          .fontSize(MARGIN_FONT_SIZE_SPACE.FOURTH_MARGIN)
          .fontColor($r('app.color.white'))
          .width(SHOW_LIST_HEIGHT_PERCENT.STACK_SHOW_SMALL_HEIGHT)
          .height(SHOW_LIST_HEIGHT_PERCENT.STACK_SHOW_SMALL_HEIGHT)
          .textAlign(this.textAl)
          .backgroundColor($r("app.color.show_list_fontColor"))
      }
      .margin({ top: MARGIN_FONT_SIZE_SPACE.FIRST_MARGIN })
      .width(ALL_PERCENT)
      .height(SHOW_LIST_HEIGHT_PERCENT.STACK_SHOW_LIST_HEIGHT)
      // set align in stack
      StackAlignRadioList()
        .margin({ top: MARGIN_FONT_SIZE_SPACE.EIGHTH_MARGIN })
    }
    .layoutWeight(1)
    .height(ALL_PERCENT)
    .width(ALL_PERCENT)
  }
}
6. 在CommonComponent.ets中,自定义组件CommonItem,代码如下:
/*
 * Copyright (c) 2022 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 { MARGIN_FONT_SIZE_SPACE } from '../common/Constants/CommonConstants';

/**
 *Show List in Column
 */
@Component
export struct CommonItem {
  @Prop item: number = 0;

  private furnitureMap: Record<number, Resource> = {
    1: $r('app.media.1'),
    2: $r('app.media.2'),
    3: $r('app.media.3'),
    4: $r('app.media.4'),
    5: $r('app.media.5'),
    6: $r('app.media.6'),
    7: $r('app.media.7')

  };

  build() {
    Column() {
      if (this.furnitureMap[this.item]) {
        Image(this.furnitureMap[this.item])
          .width(60)
          .height(60)
          .objectFit(ImageFit.Contain)
      }
    }
    .backgroundColor(Color.Transparent)
  }
}
7. 在Second.ets页面,根据首页跳转时的参数,渲染顶部不同的容器名称和条件渲染不同的子组件。
    代码如下:
/*
 * Copyright (c) 2022 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 router from '@ohos.router';
import { FlexShowList } from '../view/FlexShowList';
import { ColumnShowList } from '../view/ColumnShowList';
import { RowShowList } from '../view/RowShowList';
import { StackComponent } from '../view/StackComponent';
import {
  MARGIN_FONT_SIZE_SPACE,
  COMMON_FONT_WEIGHT,
  LIST,
  ATTRIBUTE,
  CONTAINER_TYPE,
  ALL_PERCENT
} from '../common/Constants/CommonConstants';
import { ContainerModuleItem } from '../viewmodel/ContainerModuleItem';
import { router } from '@kit.ArkUI';

/**
 *second page
 */
@Entry
@Component
struct Second {
  private moduleList: ContainerModuleItem[] = [];
  private componentName: string = '';
  @Provide containerType: number = 0;
  @Provide currentFlexDirection: FlexDirection = FlexDirection.Column;
  @Provide currentFlexJustifyContent: FlexAlign = FlexAlign.Start;
  @Provide currentFlexAlignItems: ItemAlign = ItemAlign.Start;
  @Provide currentFlexWrap: FlexWrap = FlexWrap.NoWrap;
  @Provide currentFlexAlignContent: FlexAlign = FlexAlign.Start;
  @Provide currentColumnJustifyContent: FlexAlign = FlexAlign.Start;
  @Provide currentColumnAlignItems: HorizontalAlign = HorizontalAlign.Start;
  @Provide currentRowJustifyContent: FlexAlign = FlexAlign.Start;
  @Provide currentRowAlignItems: VerticalAlign = VerticalAlign.Top;
  @Provide currentStackAlignContent: Alignment = Alignment.TopStart;
  @Provide message: string = ATTRIBUTE.TOP_START;
  @Provide list: number[] = LIST;

  aboutToAppear() {
    let params = router.getParams() as Record<string, Object>;
    this.moduleList = params.moduleList as ContainerModuleItem[];
    this.componentName = params.componentName as string;
    this.containerType = params.containerType as number;
  }

  build() {
    Row() {
      Column({ space: MARGIN_FONT_SIZE_SPACE.SIXTH_MARGIN }) {
        Column() {
          BackComp({ componentName: this.componentName })
          if (this.containerType === CONTAINER_TYPE.FLEX) {
            FlexShowList()
          } else if (this.containerType === CONTAINER_TYPE.COLUMN) {
            ColumnShowList()
          } else if (this.containerType === CONTAINER_TYPE.ROW) {
            RowShowList()
          } else {
            StackComponent()
          }
        }
        .width(ALL_PERCENT)
        .height(ALL_PERCENT)
      }
      .width(ALL_PERCENT)
    }
    .height(ALL_PERCENT)
  }
}

@Component
struct BackComp {
  private backIconResource: Resource = $r('app.media.icon_back');
  private componentName: string = '';

  build() {
    Row() {
      Image(this.backIconResource)
        .width(MARGIN_FONT_SIZE_SPACE.SEVENTH_MARGIN)
        .height(MARGIN_FONT_SIZE_SPACE.SEVENTH_MARGIN)
        .onClick(() => {
          router.back();
        })
      Text(this.componentName)
        .fontColor(Color.Black)
        .fontSize(MARGIN_FONT_SIZE_SPACE.SEVENTH_MARGIN)
        .fontWeight(COMMON_FONT_WEIGHT)
        .margin({ left: MARGIN_FONT_SIZE_SPACE.SECOND_MARGIN })
    }
    .width(ALL_PERCENT)
    .margin({ left: MARGIN_FONT_SIZE_SPACE.SECOND_MARGIN, top: MARGIN_FONT_SIZE_SPACE.SEVENTH_MARGIN })
    .justifyContent(FlexAlign.Start)
  }
}

新增场景适配

军事化指令系统重构

    * CommonContant.ets部分修改代码如下
export const enum ATTRIBUTE {
    ROW = '横排站',           // 水平排列指令
    COLUMN = '顺序站',         // 垂直顺序排列指令  
    COLUMN_REVERSE = '反序站', // 垂直反向排列指令
    NOWRAP = 'NoWrap',        // 不换行模式
    WRAP = 'Wrap',            // 换行模式
    WRAP_REVERSE = 'WrapReverse', // 反向换行模式
    START = '左对齐',          // 起始对齐指令
    CENTER = '居中对齐',       // 居中对齐指令
    END = '右对齐',           // 末端对齐指令
    TOP = '靠后站',           // 顶部对齐指令
    BOTTOM = '靠前站',        // 底部对齐指令
    TOP_START = '中间站',      // 左上角定位
    TOP_END = '右上角站',      // 右上角定位
    BOTTOM_START = '左下角站',  // 左下角定位
    BOTTOM_END = '右下角站'    // 右下角定位
};

布局容器视觉化改造

    * Column布局容器、Flex布局容器、Row布局容器均新增操场的背景图片,适配小兵排队的场景
.backgroundImage($r('app.media.img'))  //新增背景图片
        .backgroundImageSize(ImageSize.Cover)   //背景图片覆盖
        .backgroundImagePosition(Alignment.Center) //背景定位
        + 例(Column布局容器定制,ColumnShowList.ets修改代码如下)
build() {
    Column() {
        Column() {
            ForEach(LIST, (item: number) => {
                CommonItem({ item: item })
            }, (item: number) => JSON.stringify(item))
        }
        .alignItems(this.currentColumnAlignItems)
        .justifyContent(this.currentColumnJustifyContent)
        .padding(MARGIN_FONT_SIZE_SPACE.COMMON_PADDING)
        .width(ALL_PERCENT)
        .height(SHOW_LIST_HEIGHT_PERCENT.COLUMN_ROW_SHOW_LIST_HEIGHT)
        .backgroundImage($r('app.media.img'))
        .backgroundImageSize(ImageSize.Cover)
        .backgroundImagePosition(Alignment.Center)
        .margin({ top: MARGIN_FONT_SIZE_SPACE.EIGHTH_MARGIN })
}

小兵组件可视化重构

    * 数字-图片映射
        + CommonCoponent.ets代码如下
/*
 * Copyright (c) 2022 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 { MARGIN_FONT_SIZE_SPACE } from '../common/Constants/CommonConstants';

/**
 *Show List in Column
 */
@Component
export struct CommonItem {
  @Prop item: number = 0;

  private furnitureMap: Record<number, Resource> = {
    1: $r('app.media.1'),
    2: $r('app.media.2'),
    3: $r('app.media.3'),
    4: $r('app.media.4'),
    5: $r('app.media.5'),
    6: $r('app.media.6'),
    7: $r('app.media.7')

  };

  build() {
    Column() {
      if (this.furnitureMap[this.item]) {
        Image(this.furnitureMap[this.item])
          .width(60)
          .height(60)
          .objectFit(ImageFit.Contain)
      }
    }
    .backgroundColor(Color.Transparent)
  }
}

总结

- 目前你已经成功完成了 Codelab 并且学到了如何在四种常用的布局容器内,如何灵活的使用下列属性和参数:
    * **justifyContent**:作用在布局容器上,设置主轴的对齐方式。
    * **alignItems**:作用在布局容器上,设置交叉轴对齐方式。Flex 布局容器内子组件单行/列时生效,多行/列时不生效。
    * **alignContent**:作用在布局容器上,在 Flex 布局容器中设置交叉轴对齐方式,在 Stack 布局容器中设置容器内子组件整体的对齐方式。Flex 布局容器内子组件多行/列时生效,单行/列时不生效。
    * **alignSelf**:作用在子组件上,当想要布局容器内的某个子组件不按布局容器交叉轴方向设置的对齐方式排列时,可以用该属性覆盖 alignItems 的配置。
    * **align**:作用在子组件上,设置组件内容在组件范围内的对齐方式,只有当组件设置的 width 和 height 大小超过组件本身内容大小时生效。 如果组件有相应的属性设置对齐方式,比如 text 组件的 textAlign 属性,可使用 align 搭配 textAlign一起使用来实现自己的UI布局。

Introduction

OpenHarmony 6.0 适配攻坚 —— 从 API9 到 API20 的应用升级实践

Customize your domain