img

概述

本教程将详细介绍如何在HarmonyOS应用中实现一个功能完整的景点详情页面。我们将学习如何使用Swiper组件创建图片轮播、实现响应式布局,以及如何展示景点详细信息。

核心功能

  • 图片轮播展示
  • 景点信息展示
  • 加载状态管理
  • 响应式布局适配

代码实现

1. 页面状态定义

@Entry
@Component
struct ScenicSpotsDetail {
  @StorageProp('currentBreakpoint') currentBreakpoint: string = 'sm';
  @State title: string = '景点详情';
  @State detailData: strategyChild[] = []
  @State nowSpotsData: strategyChild = new strategyChild()
  @State loadingStatus: string = ''
}

2. 轮播图组件实现

@Builder
swiperItem(object: strategyChild) {
  Stack() {
    Image(object.coverUrl)
      .width(StyleConstants.FULL_WIDTH)
      .objectFit(ImageFit.Fill)
      .aspectRatio(2.5)
      .borderRadius(StyleConstants.CARD_RADIUS)

    Row() {
      Text(object.title)
        .fontColor($r('app.color.white'))
        .fontWeight(300)
        .width('90%')
        .maxLines(1)
        .fontSize($r('app.float.small_font_size'))
        .textOverflow({ overflow: TextOverflow.Ellipsis })
    }
    .backgroundColor($r('app.color.forty_alpha_black'))
  }
}

3. 数据加载实现

getDetailData() {
  this.loadingStatus = LoadingStatus.LOADING
  this.loadObjectInfo().then(async (res: ObjectTypeInfo) => {
    this.detailData = await cloud.database({ objectTypeInfo: res })
      .collection(strategyChild)
      .query()
      .equalTo('strategyId', this.scenicSpotsParentId)
      .get();
    this.loadingStatus = LoadingStatus.SUCCESS
    this.nowSpotsData = this.detailData[0]
  }).catch(() => {
    this.loadingStatus = LoadingStatus.FAILED
  })
}

页面布局

1. 主要内容区域

Column() {
  // 标题区域
  Row() {
    Text(this.nowSpotsData.title)
      .maxLines(2)
      .textOverflow({ overflow: TextOverflow.Ellipsis })
      .fontSize(18)
  }
  .backgroundColor($r('app.color.white'))
  .width('80%')
  .borderRadius(20)

  // 图片展示
  Row() {
    Image(this.nowSpotsData.coverUrl)
      .width('100%')
      .aspectRatio(2.5)
      .borderRadius(20)
  }
  .width('80%')

  // 描述信息
  Column() {
    Text('景点描述')
      .fontSize($r('app.float.huge_font_size'))
    Text(this.nowSpotsData.description)
      .fontSize('18fp')
      .lineHeight('25fp')
  }
  .backgroundColor($r('app.color.white'))
  .padding(25)
}

关键技术点

1. 加载状态管理

使用状态枚举管理页面加载状态:

if (this.loadingStatus === LoadingStatus.LOADING) {
  MyLoadingProgress()
} else if (this.loadingStatus === LoadingStatus.FAILED) {
  notFound()
} else {
  // 展示内容
}

2. 响应式轮播图

根据屏幕尺寸调整轮播图显示:

Swiper() {
  ForEach(this.detailData, (item) => {
    this.swiperItem(item)
  })
}
.displayCount(this.currentBreakpoint === 'sm' ? 1 : 2)
.indicator(this.currentBreakpoint === BreakpointConstants.BREAKPOINT_SM ?
  new DotIndicator() : false)

最佳实践

  1. 使用Stack组件叠加显示图片和文字
  2. 实现加载状态和错误处理
  3. 使用响应式布局适应不同屏幕
  4. 合理组织组件结构提高复用性

总结

通过本教程,我们学习了如何实现一个功能完整的景点详情页面。重点掌握了HarmonyOS中的Swiper组件使用、响应式布局设计、状态管理等关键技术。这些知识将帮助开发者构建更好的HarmonyOS应用界面。

Logo

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

更多推荐