HarmonyOS NEXT 实战之元服务:静态多案例效果---音乐清单

2024-12-25 17:17:07
8次阅读
0个评论

背景:

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

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

16.png

17.png

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

  • Index
import { authentication } from '@kit.AccountKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { EventMyItem } from './EventMyItem';

@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(['清单一:“温暖治愈系” 收藏清单',
          '清单二:“经典怀旧风” 收藏清单',
          '清单三:“流行动感派” 收藏清单',
          '清单四:“民谣情怀” 收藏清单',
          '清单五:“影视原声集” 收藏清单',
        ], (item: string) => {
          ListItem() {
            EventMyItem({ 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

@Preview
@ComponentV2
export struct EventMyItem {
  @Param title: string = ''

  build() {
    Column() {
      Row({ space: 6 }) {
        Text(this.title)
          .fontColor('#222222')
          .fontSize(16)
          .maxLines(2)
          .textOverflow({ overflow: TextOverflow.Ellipsis })
          .layoutWeight(1)
        if (this.title == '清单一:“温暖治愈系” 收藏清单'||this.title == '清单三:“流行动感派” 收藏清单') {
          Image($r('app.media.startIcon')).width(54).height(28)
        }

      }.width("100%")
      .justifyContent(FlexAlign.SpaceBetween)
      .alignItems(VerticalAlign.Top)


      Row() {

        this.textNum(generateFiveDigitRandomNumber() + '', '相关评论', '#9975E5')
        this.textNum(generateFiveDigitRandomNumber() + '', '上热搜数', '#FFE6960C')


      }
      .width("100%")
      .height(48)
      .justifyContent(FlexAlign.SpaceAround)


      Row() {
        Text(`${generateRandomDate()}~${generateRandomDate()}`)
          .fontSize(11)
          .fontColor('#505050')
          .layoutWeight(1)
        Image($r('app.media.ic_delete_gray')).width(28).padding(6).onClick(() => {

        })
      }.width("100%")

    }
    .width("100%")
    .margin({ top: 4, bottom: 4 })
    .padding({
      right: 12,
      left: 12,
      top: 8,
      bottom: 6
    })
    .border({ width: 1, radius: 8, color: '#F0F0F0' })
    .linearGradient({
      angle: 180,
      colors: [["#E5F3FF", 0.3], [Color.White, 0.7]]
    })
  }


  @Builder
  textNum(num: string, text: string, numFontColor: ResourceColor, isIncrease: number = -1) {
    Column() {
      if (isIncrease != -1) {

        Text() {
          Span(num)
          // ImageSpan
        }
        .fontSize(14)
        .fontColor(isIncrease == 1 ? numFontColor : (isIncrease == 2 ? '#0BB746' : '#FFE6960C'))
        .fontWeight(FontWeight.Bold)
      } else {
        Text(num).fontSize(14).fontColor(numFontColor).fontWeight(FontWeight.Bold)
      }
      Text(text).fontSize(10).fontColor('#505050')
    }
  }
}


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 generateFiveDigitRandomNumber(): number {
  const min = 100; // 五位数的最小值
  const max = 999; // 五位数的最大值
  return Math.floor(Math.random() * (max - min + 1)) + min;
}


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

  • Index
import { authentication } from '@kit.AccountKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { EventMyItem } from './EventMyItem';

@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(['清单一:“心灵慰藉之歌”',
          '清单二:“活力激情之选”',
          '清单三:“古典优雅乐章”',
          '清单四:“浪漫爱情旋律”',
          '清单五:“影视怀旧金曲”',
        ], (item: string) => {
          ListItem() {
            EventMyItem({ 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

@Preview
@ComponentV2
export struct EventMyItem {
  @Param title: string = ''

  build() {
    Column() {
      Row({ space: 6 }) {
        Text(this.title)
          .fontColor('#222222')
          .fontSize(16)
          .maxLines(2)
          .textOverflow({ overflow: TextOverflow.Ellipsis })
          .layoutWeight(1)


      }.width("100%")
      .justifyContent(FlexAlign.SpaceBetween)
      .alignItems(VerticalAlign.Top)


      Row() {
        this.textNum(generateFiveDigitRandomNumber() + '', '全部信息', Color.Blue)
        this.textNum(generateFiveDigitRandomNumber() + '', '相关评论', '#9975E5')
        this.textNum(generateFiveDigitRandomNumber() + '', '近一小时', '#E65441')
        this.textNum(generateFiveDigitRandomNumber() + '', '上热搜数', '#FFE6960C')


      }
      .width("100%")
      .height(48)
      .justifyContent(FlexAlign.SpaceAround)


      Row() {
        Text(`${generateRandomDate()}~${generateRandomDate()}`)
          .fontSize(11)
          .fontColor('#505050')
          .layoutWeight(1)

        Image($r('app.media.ic_edit_gray')).width(28).padding(6)
        // Image($r('app.media.ic_delete_gray')).width(28).padding(6).onClick(() => {
        //
        // })
      }.width("100%")

    }
    .width("100%")
    .margin({ top: 4, bottom: 4 })
    .padding({
      right: 12,
      left: 12,
      top: 8,
      bottom: 6
    })
    .border({ width: 1, radius: 8, color: '#F0F0F0' })
    .linearGradient({
      angle: 90,
      colors: [["#FFD642", 0.3], [Color.White, 0.7],['#C94F4F', 0.3]]
    })
  }
  
  @Builder
  textNum(num: string, text: string, numFontColor: ResourceColor, isIncrease: number = -1) {
    Column() {
      if (isIncrease != -1) {

        Text() {
          Span(num)
          // ImageSpan
        }
        .fontSize(14)
        .fontColor(isIncrease == 1 ? numFontColor : (isIncrease == 2 ? '#0BB746' : '#FFE6960C'))
        .fontWeight(FontWeight.Bold)
      } else {
        Text(num).fontSize(14).fontColor(numFontColor).fontWeight(FontWeight.Bold)
      }
      Text(text).fontSize(10).fontColor('#505050')
    }
  }
}


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 generateFiveDigitRandomNumber(): number {
  const min = 100; // 五位数的最小值
  const max = 999; // 五位数的最大值
  return Math.floor(Math.random() * (max - min + 1)) + min;
}


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

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

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

收藏00

登录 后评论。没有帐号? 注册 一个。