HarmonyOS NEXT 实战之元服务:静态案例效果---最近播放音乐
背景:
前几篇学习了元服务,后面几期就让我们开发简单的元服务吧,里面丰富的内容大家自己加,本期案例 仅供参考
先上本期效果图 ,里面图片自行替换
效果图1完整代码案例如下:
- Index
import { authentication } from '@kit.AccountKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { TypeShortVideoItem } from './TypeShortVideoItem';
@Entry
@Component
struct Index {
@State message: string = 'Hello World';
build() {
Column() {
Text($r('app.string.EntryAbility_label')).fontSize(20).margin({ bottom: 10 })
List({ space: 6 }) {
ForEach(['《星辰大海》- 黄霄雲',
'《青花瓷》- 周杰伦',
'《追光者》- 岑宁儿',
'《小幸运》- 田馥甄',
'《野狼 disco》- 宝石 Gem',
], (item: string) => {
ListItem() {
TypeShortVideoItem({ title: item })
}
})
}
}
.alignItems(HorizontalAlign.Start)
.height('100%')
.padding(8)
.width('100%')
.margin({ top: 40 })
}
aboutToAppear() {
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
this.loginWithHuaweiID();
}
/**
* Sample code for using HUAWEI ID to log in to atomic service.
* According to the Atomic Service Review Guide, when a atomic service has an account system,
* the option to log in with a HUAWEI ID must be provided.
* The following presets the atomic service to use the HUAWEI ID silent login function.
* To enable the atomic service to log in successfully using the HUAWEI ID, please refer
* to the HarmonyOS HUAWEI ID Access Guide to configure the client ID and fingerprint certificate.
*/
private loginWithHuaweiID() {
// Create a login request and set parameters
let loginRequest = new authentication.HuaweiIDProvider().createLoginWithHuaweiIDRequest();
// Whether to forcibly launch the HUAWEI ID login page when the user is not logged in with the HUAWEI ID
loginRequest.forceLogin = false;
// Execute login request
let controller = new authentication.AuthenticationController();
controller.executeRequest(loginRequest).then((data) => {
let loginWithHuaweiIDResponse = data as authentication.LoginWithHuaweiIDResponse;
let authCode = loginWithHuaweiIDResponse.data?.authorizationCode;
// Send authCode to the backend in exchange for unionID, session
}).catch((error: BusinessError) => {
hilog.error(0x0000, 'testTag', 'error: %{public}s', JSON.stringify(error));
if (error.code == authentication.AuthenticationErrorCode.ACCOUNT_NOT_LOGGED_IN) {
// HUAWEI ID is not logged in, it is recommended to jump to the login guide page
}
});
}
}
- Item
@Extend(Image)
function imageExtend(width: Length, height: Length) {
.width(width)
.height(height)
}
@Preview
@ComponentV2
export struct TypeShortVideoItem {
@Param title: string = ''
build() {
Column() {
RelativeContainer() {
Image('')
.borderRadius({ topLeft: 8, topRight: 8 })
.backgroundColor('#565656')
.width('100%')
.height(170)
.alignRules({
left: { anchor: '__container__', align: HorizontalAlign.Start },
right: { anchor: '__container__', align: HorizontalAlign.End }
})
.id('bg_img_single_top')
Image($r('app.media.ic_video_cover'))
.height(170)
.alignRules({
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
.id('img_single_top')
Image($r('app.media.ic_video_item_attitude_positive'))
.imageExtend(30, 28)
.id('iv_attitude')
.alignRules({
left: { anchor: '__container__', align: HorizontalAlign.Start }
})
Text(` ${generateFiveDigitRandomNumber()+''}S `)
.fontSize(11)
.fontColor('#ffffff')
.backgroundColor('#CC222222')
.borderRadius(2)
.id('tv_video_duration')
.margin({ left: 8, bottom: 8, top: 146 })
Column() {
// Image($r('app.media.ic_video_item_similar')).width(13)
// Text('12').fontSize(11).fontColor('#ffffff')
// .margin({ top: 2, bottom: 6 })
Image($r('app.media.ic_video_item_like')).width(13)
Text(generateFiveDigitRandomNumber()+'').fontSize(11).fontColor('#ffffff')
.margin({ top: 2, bottom: 6 })
Image($r('app.media.ic_video_item_comment')).width(13)
Text(generateFiveDigitRandomNumber()+'').fontSize(11).fontColor('#ffffff')
.margin({ top: 2, bottom: 6 })
Image($r('app.media.ic_video_item_collection')).width(13)
Text(generateFiveDigitRandomNumber()+'').fontSize(11).fontColor('#ffffff')
.margin({ top: 2, bottom: 6 })
}
.alignRules({
left: { anchor: 'iv_web_logo', align: HorizontalAlign.Start },
bottom: { anchor: "iv_web_logo", align: VerticalAlign.Bottom }
})
.id('cl_right')
.margin({ left: 3, bottom: 28 })
ImageTextShortVideo(this)
Image($r('app.media.app_icon'))
.width(20)
.borderRadius(10)
.margin({ top: 140, right: 8, bottom: 8 })
.alignRules({
right: { anchor: '__container__', align: HorizontalAlign.End },
})
.id('iv_web_logo')
Text(generateRandomDate())
.fontSize(11)
.fontColor('#505050')
.id('tv_item_time')
.alignRules({ bottom: { anchor: 'll_item_author_avatar', align: VerticalAlign.Top } })
.margin({ left: 8 })
Row() {
Image($r('app.media.zuijinmusic')).width(16).borderRadius(8)
Text(generateFiveCharacterRandomString()).fontSize(11).fontColor('#505050').margin({ left: 4, right: 4 })
Text('发布于 北京').fontSize(11).fontColor('#666666').margin({ left: 4, right: 4 })
Blank()
Image($r('app.media.ic_item_more')).width(16)
.onClick(() => {
})
}
.width('100%')
.height(36)
.id('ll_item_author_avatar')
.alignRules({ bottom: { anchor: '__container__', align: VerticalAlign.Bottom } })
.padding({ left: 8, right: 8 })
//是否选中状态
Row() {
Toggle({ type: ToggleType.Checkbox, isOn: true }).width(21)
}
.width('100%')
.height(276)
.backgroundColor('#4D000000')
.justifyContent(FlexAlign.End)
.alignItems(VerticalAlign.Top)
.borderRadius(8)
.id('cl_back')
.alignRules({
right: { anchor: '__container__', align: HorizontalAlign.End }
})
.visibility(Visibility.None)
}
.width('100%')
.height(276)
.border({ width: 1, color: '#E3E3E3', radius: 8 })
}
//测试用 .width(px2vp(display.getDefaultDisplaySync().width)/2-10)
.width('100%')
// .height('100%')
}
}
/** 短视频专属图片+文字 */
@Builder
export function ImageTextShortVideo(text: TypeShortVideoItem) {
Text() {
Span(text.title)
.fontColor('#222222').fontSize(14).fontWeight(FontWeight.Bold)
}
.width('100%')
.maxLines(2)
.lineHeight(20)
.textOverflow({ overflow: TextOverflow.Ellipsis })
.padding({ left: 8, top: 8, right: 8 })
.alignRules({ top: { anchor: 'bg_img_single_top', align: VerticalAlign.Bottom } })
}
function generateRandomDate(): string {
const minYear = 2023; // 最小年份
const maxYear = 2024; // 最大年份
const minMonth = 1; // 最小月份
const maxMonth = 12; // 最大月份
const minDay = 1; // 最小日期
const maxDay = 31; // 最大日期
// 生成随机年份
const year = Math.floor(Math.random() * (maxYear - minYear + 1)) + minYear;
// 生成随机月份
const month = Math.floor(Math.random() * (maxMonth - minMonth + 1)) + minMonth;
// 根据月份生成合理的日期
let day = 0;
if ([1, 3, 5, 7, 8, 10, 12].includes(month)) {
day = Math.floor(Math.random() * (31 - minDay + 1)) + minDay;
} else if ([4, 6, 9, 11].includes(month)) {
day = Math.floor(Math.random() * (30 - minDay + 1)) + minDay;
} else if (month === 2) {
// 处理闰年
if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {
day = Math.floor(Math.random() * (29 - minDay + 1)) + minDay;
} else {
day = Math.floor(Math.random() * (28 - minDay + 1)) + minDay;
}
}
// 返回格式化的日期字符串
return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
}
function generateFiveCharacterRandomString(): string {
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let result = '';
for (let i = 0; i < 5; i++) {
result += characters.charAt(Math.floor(Math.random() * characters.length));
}
return result;
}
function generateFiveDigitRandomNumber(): number {
const min = 100; // 五位数的最小值
const max = 999; // 五位数的最大值
return Math.floor(Math.random() * (max - min + 1)) + min;
}
最近文章>>>>>>>>>>>
HarmonyOS NEXT实战:元服务与应用 APP 发布应用市场的详细步骤与流程
若本文对您稍有帮助,诚望您不吝点赞,多谢。
有兴趣的同学可以点击查看源码
- gitee:https://gitee.com/jiaojiaoone/explore-harmony-next/tree/case%2Fwanandroid/
- github:https://github.com/JasonYinH/ExploreHarmonyNext.git