• 鸿蒙HarmonyOS开发:如何灵活运用服务卡片提升用户体验


    一、ArkTS卡片相关模块

    在这里插入图片描述

    ArkTS卡片创建完成后,工程中会新增如下卡片相关文件:卡片生命周期管理文件(EntryFormAbility.ets)、卡片页面文件(WidgetCard.ets)和卡片配置文件(form_config.json)。

    在这里插入图片描述

    二、卡片事件能力说明

    ArkTS卡片中提供了postCardAction接口用于卡片内部和提供方应用间的交互,当前支持router、message和call三种类型的事件,仅在卡片中可以调用。

    在这里插入图片描述

    三、卡片事件的主要使用场景

    • router事件:可以使用router事件跳转到指定UIAbility,并通过router事件刷新卡片内容。

    • call事件:可以使用call事件拉起指定UIAbility到后台,并通过call事件刷新卡片内容。

    • message事件:可以使用message拉起FormExtensionAbility,并通过FormExtensionAbility刷新卡片内容。

    3.1、使用router事件跳转到指定UIAbility

    在卡片中使用postCardAction接口的router能力,能够快速拉起卡片提供方应用的指定UIAbility,因此UIAbility较多的应用往往会通过卡片提供不同的跳转按钮,实现一键直达的效果。

    3.1.1、卡片内按钮跳转到应用的不同页面

    在UIAbility中接收router事件并获取参数,根据传递的params不同,选择拉起不同的页面。

    // Entryability.ts

    import UIAbility from '@ohos.app.ability.UIAbility';
    import hilog from '@ohos.hilog';
    import window from '@ohos.window';
    
    export default class EntryAbility extends UIAbility {
      // 服务卡片跳转的页面
      private selectPage: string = '';
      //当前windowStage
      private currentWindowStage: window.WindowStage | null = null;
    
      // 如果UIAbility第一次启动,在收到Router事件后会触发onCreate生命周期回调
      onCreate(want, launchParam) {
        // 获取router事件中传递的targetPage参数
        if (want.parameters !== undefined && want.parameters.params) {
          let params = JSON.parse(want.parameters.params)
          this.selectPage = params.targetPage
        }
      }
    
      // 如果UIAbility已在后台运行,在收到Router事件后会触发onNewWant生命周期回调
      onNewWant(want, launchParam) {
        // 获取router事件中传递的targetPage参数
        if (want.parameters !== undefined && want.parameters.params) {
          let params = JSON.parse(want.parameters.params)
          this.selectPage = params.targetPage
        }
        this.onWindowStageCreate(this.currentWindowStage)
      }
    
      // 创建主窗口,为此功能设置主页
      onWindowStageCreate(windowStage: window.WindowStage) {
        let targetPage = this.selectPage || "Index"
        targetPage = "pages/" + targetPage
        // 为currentWindowStage赋值
        if (this.currentWindowStage === null) {
          this.currentWindowStage = windowStage;
        }
        windowStage.loadContent(targetPage, (err, data) => {
          if (err.code) {
            hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
            return;
          }
          hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
        });
      }
    }
    
    
    3.1.2、服务卡片的点击跳转事件

    在卡片页面中布局两个按钮,点击其中一个按钮时调用postCardAction向指定UIAbility发送router事件,并在事件内定义需要传递的内容。

    // WidgetCard.ets

    @Entry
    @Component
    struct WidgetCard {
    
      build() {
        Column(){
          Button("个人中心")
            .onClick(() => {
              postCardAction(this, {
                "action": "router",
                "abilityName": "EntryAbility",
                "params": {
                  "targetPage": "Personals"
                }
              });
            })
    
          Button("消息列表")
            .onClick(() => {
              postCardAction(this, {
                "action": "router",
                "abilityName": "EntryAbility",
                "params": {
                  "targetPage": "Message"
                }
              });
            })
        }
        .width("100%")
        .height("100%")
        .justifyContent(FlexAlign.Center)
      }
    }
    
    3.2、通过message事件刷新卡片内容

    在卡片页面中可以通过postCardAction接口触发message事件拉起FormExtensionAbility,然后由FormExtensionAbility刷新卡片内容。

    3.2.1、在卡片页面调用postCardAction接口触发message事件

    在卡片页面通过注册Button的onClick点击事件回调,并在回调中调用postCardAction接口触发message事件拉起FormExtensionAbility。卡片页面中使用LocalStorageProp装饰需要刷新的卡片数据。

    // WidgetCard.ets

    let storageUpdateByMsg = new LocalStorage();
    
    @Entry(storageUpdateByMsg)
    @Component
    struct UpdateByMessageCard {
      @LocalStorageProp('title') title: ResourceStr = 'title';
      @LocalStorageProp('detail') detail: ResourceStr = 'detail';
    
      build() {
        Column() {
          Text(this.title)
          Text(this.detail)
          Button("刷新数据")
            .onClick(() => {
              postCardAction(this, {
                "action": "message",
                "params": {
                  "msgTest": "messageEvent"
                }
              });
            })
        }
        .width("100%")
        .height("100%")
        .justifyContent(FlexAlign.Center)
      }
    }
    
    3.2.2、onFormEvent生命周期中调用updateForm接口刷新卡片

    在FormExtensionAbility的onFormEvent生命周期中调用updateForm接口刷新卡片。

    // EntryFormAbility.ts

    import formInfo from '@ohos.app.form.formInfo';
    import formBindingData from '@ohos.app.form.formBindingData';
    import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
    import formProvider from '@ohos.app.form.formProvider';
    
    export default class EntryFormAbility extends FormExtensionAbility {
      onAddForm(want) {
        // Called to return a FormBindingData object.
        let formData = {};
        return formBindingData.createFormBindingData(formData);
      }
    
      onFormEvent(formId, message) {
        class FormDataClass {
          title: string = 'Title Update.'; // 和卡片布局中对应
          detail: string = 'Description update success.'; // 和卡片布局中对应
        }
    
        let formData = new FormDataClass();
        let formInfo: formBindingData.FormBindingData = formBindingData.createFormBindingData(formData);
        formProvider.updateForm(formId, formInfo)
        .then(() => {})
        .catch((error) => {})
      }
    
    };
    
    
    3.2.2、运行效果如下图所示

    在这里插入图片描述

  • 相关阅读:
    三大数据库 sequence 之华山论剑 (下篇)
    React Refs 使用场景及核心要点
    Node.js全栈指南:认识MIME和HTTP
    全栈知识体系
    【LeetCode】【前K个高频单词】
    MySQL读写分离原理
    若依前后端分离版开源项目学习
    遥感指数数据库
    算法竞赛入门【码蹄集进阶塔335题】(MT2321-2325)
    超简单的抖音去水印
  • 原文地址:https://blog.csdn.net/shanghai597/article/details/140384125