自学内容网 自学内容网

HarmonyOS NEXT 实战之元服务:静态案例效果--- 歌手推荐

背景:

前几篇学习了元服务,后面几期就让我们开发简单的元服务吧,里面丰富的内容大家自己加,本期案例 仅供参考

先上本期效果图 ,里面图片自行替换

在这里插入图片描述

效果图1完整代码案例如下:

import { authentication } from '@kit.AccountKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';

@Entry
@ComponentV2
struct Index {
  @Local threeArrChild: CheckModel[] = GetThreeLevelWeiBoData
  @Local hotTypeChild: string = '0'
  @Local hotType: string = '2'
  @Local threeArr: CheckModel[] = GetThreeLevelWeiBoData

  build() {
    Column({space:10}) {
      Text($r('app.string.EntryAbility_label')).fontSize(25)
      threeLevel(this)
      listData(this)
    }
    .alignItems(HorizontalAlign.Start)
    .height('100%')
    .width('100%')
    .margin({ top: 50 }).padding(16)
  }

  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

      }
    });
  }
}

@ObservedV2
export class CheckModel {
  name: ResourceStr = ''
  value: string = ''
  @Trace checked: boolean = false

  constructor(name: ResourceStr, value: string, checked: boolean = false) {
    this.name = name
    this.value = value
    this.checked = checked
  }
}

@Builder
function threeLevel(searchAllThis: Index) {

  List() {

    ForEach(searchAllThis.threeArr, (item: CheckModel, index: number) => {
      ListItem() {

        Text(item.name)
          .height('100%')
          .fontSize(14)
          .fontColor(item.checked ? "#5090F1" : '#666666')
          .margin({ right: 16 })
          .onClick(() => {
            if (item.checked) {
              return
            }
            for (let i = 0; i < searchAllThis.threeArr.length; i++) {
              searchAllThis.threeArr[i].checked = false
            }
            for (let i = 0; i < searchAllThis.threeArr.length; i++) {

            }
            item.checked = true

            searchAllThis.hotTypeChild = item.name + ''
            //todo 模拟数据
            searchAllThis.threeArrChild = GetThreeLevelWeiBoData

          })

      }
    }, (item: CheckModel, index: number) => {
      //每个tab下都有相同数据: 如 “热榜” ,键值生成函数不能相同
      return searchAllThis.hotType + '__' + JSON.stringify(item) + '__' + index
    })
  }
  .width('100%')
  .height(14)
  .listDirection(Axis.Horizontal)
  .scrollBar(BarState.Off)
}

export const GetThreeLevelWeiBoData: CheckModel[] = [
  new CheckModel('热榜', '0', true),
  new CheckModel('国内榜', '2'),
  new CheckModel('实时上升榜', '3'),
  new CheckModel('国外榜', '1'),
]

/** 列表数据 */
@Builder
function listData(searchAllThis: Index) {
  List({ space: 2 }) {
    ForEach(searchAllThis.threeArrChild, (item: string, index: number) => {
      ListItem() {
        Row({ space: 4 }) {

          Text(`${index + 1}`)
            .width(16)
            .height(16)
            .fontSize(10)
            .fontColor(Color.White)
            .textAlign(TextAlign.Center)
            .backgroundImage(index == 0 ? $r('app.media.ic_hot_no1') : (index == 1 ? $r('app.media.ic_hot_no2') :
              (index == 2 ? $r('app.media.ic_hot_no3') : $r('app.media.ic_hot_no_other'))))
            .backgroundImageSize(ImageSize.Cover)


          Text(generateFiveCharacterRandomString() + '__' +
          searchAllThis.hotTypeChild /*`衡阳市女子看守所所长夫妇大人衡阳市女子看守所所长夫妇大人`*/)
            .fontSize(14)
            .fontColor('#222222')
            .layoutWeight(1)
            .maxLines(1)
            .textOverflow({ overflow: TextOverflow.Ellipsis })
          Row({ space: 4 }) {
            Image($r('app.media.ic_hot')).width(16).height(16)
            Text(generateFiveDigitRandomNumber() + '')
              .fontSize(12).fontColor('#E65441').fontWeight(FontWeight.Bold)
          }

          Text(generateRandomDate()).fontSize(11).fontColor('#222222')
        }.width('#100%')
        .height(44)

      }
    })
  }
  .width('#100%')
  .height('#100%')
  .margin({ top: 10 })
  .layoutWeight(1)
  .padding({ right: 12 })

}

function generateFiveDigitRandomNumber(): number {
  const min = 10000; // 五位数的最小值
  const max = 99999; // 五位数的最大值
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

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 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')}`;
}

最近文章>>>>>>>>>>>

HarmonyOS NEXT实战:元服务与应用 APP 发布应用市场的详细步骤与流程

若本文对您稍有帮助,诚望您不吝点赞,多谢。

有兴趣的同学可以点击查看源码


原文地址:https://blog.csdn.net/qq_40533422/article/details/144717026

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!