img

概述

本教程将详细介绍HarmonyOS应用中的UI组件使用和样式管理,包括常用组件的使用方法、样式定义、以及响应式布局等内容。我们将通过实际项目中的代码示例来展示这些功能的实现方法。

基础组件

1. Column组件

用于垂直布局:

Column() {
  CommonNavbar({ title: this.title, inputText: this.inputText })
  // 内容区域
}
.width('100%')
.height('100%')
.backgroundColor($r('app.color.page_background'))

2. Row组件

用于水平布局:

Row() {
  Text(this.nowSpotsData.title)
    .maxLines(2)
    .textOverflow({ overflow: TextOverflow.Ellipsis })
    .fontSize(18)
}
.backgroundColor($r('app.color.white'))
.width('80%')
.justifyContent(FlexAlign.Center)

3. Stack组件

用于层叠布局:

Stack() {
  Image(object.coverUrl)
    .width(StyleConstants.FULL_WIDTH)
    .objectFit(ImageFit.Fill)
    .aspectRatio(2.5)

  Row() {
    Text(object.title)
      .fontColor($r('app.color.white'))
      .fontWeight(300)
  }
  .backgroundColor($r('app.color.forty_alpha_black'))
}

列表组件

1. List组件

List({ space: StyleConstants.SPACE_TWENTY }) {
  ListItem() {
    Column() {
      CardComponents({ hotCartList: this.hotCartList })
    }
  }
}

2. Tabs组件

Tabs({
  barPosition: this.currentBreakpoint === BreakpointConstants.BREAKPOINT_LG ? 
    BarPosition.Start : BarPosition.End,
  index: this.currentPageIndex
}) {
  TabContent() {
    Home().backgroundColor($r('app.color.page_background'))
  }
  .tabBar(this.BottonNavigation(buttonInfo[PageConstants.HOME_INDEX]))
}

图片组件

1. Image组件

Image(this.currentPageIndex === button.index ? button.selectImg : button.img)
  .objectFit(ImageFit.Contain)
  .width($r('app.float.main_image_size'))
  .height($r('app.float.main_image_size'))

2. 轮播图实现

Swiper() {
  ForEach(this.detailData, (item: strategyChild) => {
    this.swiperItem(item)
  })
}
.autoPlay(true)
.displayCount(this.currentBreakpoint === 'sm' ? 1 : 2)
.itemSpace(10)

样式管理

1. 颜色管理

.backgroundColor($r('app.color.page_background'))
.fontColor($r('app.color.focus_color'))

2. 尺寸管理

.width(StyleConstants.FULL_WIDTH)
.height(StyleConstants.FULL_HEIGHT)
.fontSize($r('app.float.micro_font_size'))

3. 边距和圆角

.padding({
  top: 15,
  bottom: 15,
  left: 10,
  right: 10
})
.borderRadius(StyleConstants.CARD_RADIUS)

自定义组件

1. Builder装饰器

@Builder
BottonNavigation(button: ButtonInfoModel) {
  Column({ space: PageConstants.BUTTON_SPACE }) {
    // 组件内容
  }
}

2. 组件复用

CommonNavbar({ 
  title: this.title, 
  inputText: this.inputText, 
  isDetail: this.isDetail 
})

总结

通过本教程,我们深入学习了HarmonyOS应用中的UI组件使用和样式管理。掌握了基础组件、列表组件、图片组件的使用方法,以及样式管理、自定义组件等关键技术。这些知识对于开发美观、易用的HarmonyOS应用至关重要。正确使用UI组件和管理样式,可以显著提升应用的用户体验。

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐