Harmonyos5应用开发实战——顶部组件的功能实现
文章内容概要
本文聚焦于HarmonyOS 5应用开发中一个顶部组件的实现。该组件具备店铺优惠信息展示、优惠券领取以及商品搜索等功能,能够为用户提供便捷的交互体验,同时实时更新数据以反映最新的店铺优惠和商品信息。
核心功能介绍
1. 组件初始化
在组件即将显示时,aboutToAppear 方法会被调用,该方法会触发 storeUpdate 和 initCoupons 方法,分别用于初始化优惠信息列表和可领取的优惠券列表。
aboutToAppear(): void {
this.storeUpdate()
this.initCoupons()
}
2. 优惠信息展示
storeUpdate 方法会将新用户优惠和满减活动信息添加到 discountList 中,然后使用 Swiper 组件循环展示这些优惠信息。
storeUpdate() {
this.discountList = []
this.discountList.push(new DiscountModel($r('app.media.icon'),
$r('app.string.new_user_discount', this.storeSet.xyhMoney)))
this.reductionList.forEach(item => {
this.discountList.push(new DiscountModel($r('app.media.icon'), item.name ?? ''))
})
}
// 展示优惠信息的 Swiper 组件
Swiper() {
ForEach(this.discountList, (item: DiscountModel) => {
Row() {
Image($r('app.media.notice')).width(16).margin({ left: 8 })
Text(item.content)
.fontColor($r('sys.color.multi_color_09'))
.fontSize($r('sys.float.Caption_M'))
.textAlign(TextAlign.Start)
.margin({ left: 4 })
.maxLines(1)
.textOverflow({ overflow: TextOverflow.Ellipsis })
.layoutWeight(1)
}.layoutWeight(1)
}, (item: DiscountModel) => (JSON.stringify(item)))
}
```##### 3. 获取当前位置
`getLocation`方法用于获取用户的当前位置,并将位置信息设置到地图控制器中。
```typescript
getLocation(mapController?: map.MapComponentController): Promise<geoLocationManager.Location> {
let promise = geoLocationManager.getCurrentLocation();
console.info('getCurrentLocation' + JSON.stringify(promise));
promise.then(async (location: geoLocationManager.Location) => {
mapController?.setMyLocation(location);
console.info('getCurrentLocation' + JSON.stringify(location));
return location;
}).catch((error: Error) => {
console.error('getCurrentLocation failed', 'getCurrentLocation error: ' + JSON.stringify(error));
});
return promise;
}
4. 跳转到花瓣地图导航
goPetalMap方法用于创建一个Want对象,指定花瓣地图的包名和URI,并传递目的地的经纬度和名称等信息,然后启动花瓣地图应用进行导航。
goPetalMap() {
let petalMapWant: Want = {
bundleName: 'com.huawei.hmos.maps.app',
uri: 'maps://routes',
parameters: {
linkSource: AppStorage.get('packageName') as string,
destinationLatitude: this.latitude,
destinationLongitude: this.longitude,
destinationPoiId: '',
destinationName: this.storeInfo?.address ?? '',
},
}
let context = getContext(this) as common.UIAbilityContext;
context.startAbility(petalMapWant);
}
5. 界面布局
在build方法中,使用NavDestination、Stack、RelativeContainer等组件进行界面布局,展示地图组件、返回按钮、定位按钮、店铺信息和导航按钮等。
build() {
NavDestination() {
Stack({ alignContent: Alignment.BottomStart }) {
RelativeContainer() {
MapComponent({ mapOptions: this.mapOption, mapCallback: this.callback })
Row() {
Row() {
Image($r('app.media.back')).width(24).height(24)
}
.width(40)
.height(40)
.backgroundColor('#0C000000')
.padding(8)
.borderRadius(1000)
.margin({ left: 13 })
.onClick(() => {
this.pageStack.pop()
})
}
.width(Constants.FULL_SIZE)
.margin({ top: this.windowTopHeight })
.constraintSize({ maxWidth: Constants.FULL_SIZE })
.padding({ bottom: 10, top: 16 })
.justifyContent(FlexAlign.Start)
.alignRules({
'top': { 'anchor': '__container__', 'align': VerticalAlign.Top },
'left': { 'anchor': '__container__', 'align': HorizontalAlign.Start },
'right': { 'anchor': '__container__', 'align': HorizontalAlign.End },
})
Image($r('app.media.my_location'))
.width(32)
.height(32)
.borderRadius(8)
.margin({ bottom: 24, right: 16 })
.alignRules({
'bottom': { 'anchor': 'bottomCol', 'align': VerticalAlign.Top },
'right': { 'anchor': '__container__', 'align': HorizontalAlign.End },
})
.onClick(() => {
if (this.myLocation) {
this.mapController?.animateCamera(map.newLatLng({
latitude: this.myLocation?.latitude,
longitude: this.myLocation?.longitude,
}, 15), 200);
}
})
Column() {
Row() {
Row() {
Image(`${CommonUrl.CLOUD_STORAGE_URL}${this.storeInfo?.logo}`).width(40).height(40).borderRadius(8)
Column() {
Text(this.storeInfo?.name)
.fontSize($r('sys.float.Body_L'))
.fontWeight(FontWeight.Medium)
.fontColor($r('sys.color.font_primary'))
.maxLines(1)
.textOverflow({ overflow: TextOverflow.Ellipsis })
Text(this.storeInfo?.address)
.fontSize($r('sys.float.Body_S'))
.fontColor($r('sys.color.font_secondary'))
.margin({ top: 2 })
.maxLines(2)
.textOverflow({ overflow: TextOverflow.Ellipsis })
}.alignItems(HorizontalAlign.Start).margin({ left: 8 }).layoutWeight(1)
}.layoutWeight(1)
Image($r('app.media.navigation')).width(40).onClick(() => {
this.goPetalMap()
})
}
.width(Constants.FULL_SIZE)
.justifyContent(FlexAlign.SpaceBetween)
}
.width(Constants.FULL_SIZE)
.borderRadius({ topLeft: 20, topRight: 20 })
.backgroundColor($r('sys.color.comp_background_list_card'))
.padding({
top: 30,
left: 24,
right: 24,
bottom: 30,
})
.alignRules({
'bottom': { 'anchor': '__container__', 'align': VerticalAlign.Bottom },
'left': { 'anchor': '__container__', 'align': HorizontalAlign.Start },
'right': { 'anchor': '__container__', 'align': HorizontalAlign.End },
})
.id('bottomCol')
}.height(Constants.FULL_SIZE)
}
}.hideTitleBar(true)
}
通过以上步骤,在HarmonyOS 5应用中成功集成了地图组件,实现了定位功能和跳转到花瓣地图导航的功能。