动态

详情 返回 返回

鴻蒙添加桌面卡片並根據尺寸顯示不同UI - 动态 详情

  1. 首先在entry/src/main/ets文件夾上右擊,選擇New->Service Widget->Dynamic Widget(或者靜態也可以)
    image.png
  2. 選擇一個模板,我這裏直接選擇Hello World
    image.png
  3. 勾選支持的尺寸與默認的尺寸,勾選完後點擊finish創建完成
    image.png
  4. 創建好後,會自動打開一個WidgetCard.ets的文件,這個文件是卡片的佈局,我們先不改動這個文件,去找到繼承FormExtensionAbility的類,這個類創建項目的時候會自動創建,其中實現包含了卡片的全部生命週期
    image.png
  5. 在創建卡片的生命週期onAddForm中,可以通過want.parameters.[formInfo.FormParam.DIMENSION_KEY]取出卡片尺寸的相關信息,再通過formBindingData.createFormBindingData創建FormBindingData對象並將尺寸信息傳入卡片,在卡片頁面根據不同尺寸信息結合業務場景適配不同的UI。卡片尺寸枚舉請參考FormDimension。
// EntryFormAbility.ets
import { formBindingData, FormExtensionAbility, formInfo } from '@kit.FormKit';
import { Want } from '@kit.AbilityKit';

export default class EntryFormAbility extends FormExtensionAbility {
  onAddForm(want: Want) {
    // Called to return a FormBindingData object.
    let dimension: string = "";
    if (want.parameters) {
      dimension = JSON.stringify(want.parameters[formInfo.FormParam.DIMENSION_KEY]) // 獲取要創建的卡片的尺寸
      console.info('dimension='+dimension)
    }
    let obj: Record<string, string> = {
      "dimension": dimension
    };
    return formBindingData.createFormBindingData(obj);
  }
  // ...
}
  1. 回到第四步中的WidgetCard.ets,在struct中插入如下代碼,用於接收尺寸信息(第5步的createFormBindingData操作中封裝了保存到本地的動作,可以直接使用LocalStorageProp獲取):
// WidgetCard.ets
// ...
  @LocalStorageProp("dimension")  dimension: string = '0' // 卡片頁面接收尺寸信息
// ...
  1. 根據dimension字段顯示不同的UI,dimension的值請參考定義卡片尺寸枚舉
@Entry
@Component
struct WidgetCard {
  readonly title: string = 'Hello World';
  readonly actionType: string = 'router';
  readonly abilityName: string = 'EntryAbility';
  readonly message: string = 'add detail';
  readonly fullWidthPercent: string = '100%';
  readonly fullHeightPercent: string = '100%';
  @LocalStorageProp("dimension") dimension: string = '0'

  build() {
    Row() {
      Image(this.dimension == "1" ? $r("app.media.1x2") :
        this.dimension == "2" ? $r("app.media.2x2") : $r("app.media.1x2"))
        .height(this.fullHeightPercent)
        .width(this.fullWidthPercent)
    }
    .height(this.fullHeightPercent)
    .onClick(() => {
      postCardAction(this, {
        action: this.actionType,
        abilityName: this.abilityName,
        params: {
          message: this.message
        }
      })
    })
  }
}
  1. 效果展示
    image.png
    image.png
    image.png
    image.png
  2. 提一嘴,除了在添加的時候可以設置支持的尺寸,在對應模塊下的resources/base/profile/form_config.json下也可以配置
    image.png
  3. 至此,本文完結
user avatar jcguanqi 头像 zourongle 头像 u_9449786 头像 didiaodekaishuiping 头像 jingmingdewudongmian_dscnyw 头像 fengdudeyema 头像 HarmonyOS5 头像 momeak9 头像 hu_qi 头像 gxx01 头像 georgegcs 头像 columsys 头像
点赞 40 用户, 点赞了这篇动态!
点赞

Add a new 评论

Some HTML is okay.