HarmonyOS NEXT 实战之元服务:静态案例效果---我的生活记录

背景:

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

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

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

  • Index

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

    @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,index:number) => {
            ListItem() {
              EventHotItem({ title: item,index:index })
            }
    
          })
    
    
        }
    
      }
      .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(Text)
    function textExtend(fontSize: number, fontColor: ResourceColor) {
    .fontSize(fontSize)
    .fontColor(fontColor)
    .maxLines(5)
    .textOverflow({ overflow: TextOverflow.Ellipsis })
    }

    @Preview
    @ComponentV2
    export struct EventHotItem {
    @Param title: string = ''
    //下标
    @Param index: number = 0;
    build() {
    Stack() {
    Column({ space: 8 }) {
    Text(this.title)
    .lineHeight(20)
    .textExtend(16, '#222222')

    复制代码
          Row() {
            Text(generateRandomDate())
              .textExtend(11, '#505050')
    
            Row({ space: 4 }) {
              Image($r('app.media.ic_hot')).width(16).height(16)
              Text(generateFiveDigitRandomNumber() + '')
                .textExtend(12, '#E65441').fontWeight(FontWeight.Bold)
            }
    
          }
          .width('100%')
          .justifyContent(FlexAlign.SpaceBetween)
        }
        .padding(12)
        .margin({ left: 8 })
        .alignItems(HorizontalAlign.Start)
        //参考 EventHotAdapter 30行
        .border({
          width: 1,
          color: this.getBorderColor(),
          radius: 8
        })
        .linearGradient({
          angle: 0,
          colors: [[Color.White, 0.1], [this.getLinearGradientColor(), 0.9]]
        })
    
        Text(`${this.index + 1}`)
          .width(16)
          .height(24)
          .textExtend(11, Color.White)
          .fontWeight(FontWeight.Bold)
          .margin({ top: 6 })
          .padding({ top: 7 })
          .textAlign(TextAlign.Center)//backgroundImage 不支持svg类型的图片 https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V2/ts-universal-attributes-background-0000001477981165-V2
          .backgroundImage(this.getTextBg())
          .backgroundImageSize(ImageSize.Cover)
    
      }
      .width('100%')
      .margin({ top: 8 })
      .padding({ left: 4, right: 12 })
      .alignContent(Alignment.TopStart)
    }
    
    getBorderColor(): ResourceColor {
      return this.index == 0 ? '#FCEDEC' : (this.index == 1 ? '#FCF4E' : (this.index == 2 ? "#EDF3FD" : '#F0F0F0'));
    }
    
    getLinearGradientColor(): ResourceColor {
      return this.index == 0 ? '#FCEDEC' : (this.index == 1 ? '#FCF4E' : (this.index == 2 ? "#EDF3FD" : Color.White));
    }
    
    getTextBg(): ResourceStr {
      return this.index == 0 ? $r('app.media.ic_hot_index_1') :
        (this.index == 1 ? $r('app.media.ic_hot_index_2') :
          (this.index == 2 ? $r('app.media.ic_hot_index_3') : $r('app.media.ic_hot_index_default')));
    }

    }

    function generateRandomDate(): string {
    const minYear = 2024; // 最小年份
    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 = 10000; // 五位数的最小值
    const max = 99999; // 五位数的最大值
    return Math.floor(Math.random() * (max - min + 1)) + min;
    }

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

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

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

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

相关推荐
雪芽蓝域zzs10 分钟前
鸿蒙Next开发 获取APP缓存大小和清除缓存
缓存·华为·harmonyos
Robot2514 小时前
「华为」人形机器人赛道投资首秀!
大数据·人工智能·科技·microsoft·华为·机器人
鸿蒙布道师4 小时前
鸿蒙NEXT开发动画案例5
android·ios·华为·harmonyos·鸿蒙系统·arkui·huawei
小诸葛的博客12 小时前
华为ensp实现跨vlan通信
网络·华为·智能路由器
康康这名还挺多14 小时前
鸿蒙HarmonyOS list优化一: list 结合 lazyforeach用法
数据结构·list·harmonyos·lazyforeach
晚秋大魔王17 小时前
OpenHarmony 开源鸿蒙南向开发——linux下使用make交叉编译第三方库——nettle库
linux·开源·harmonyos
python算法(魔法师版)21 小时前
.NET 在鸿蒙系统上的适配现状
华为od·华为·华为云·.net·wpf·harmonyos
bestadc1 天前
鸿蒙 UIAbility组件与UI的数据同步和窗口关闭
harmonyos
枫叶丹41 天前
【HarmonyOS Next之旅】DevEco Studio使用指南(二十二)
华为·harmonyos·deveco studio·harmonyos next
ax一号街阿楠1 天前
华为FAT AP配置 真机
网络·华为·智能路由器