- 首先在entry/src/main/ets文件夾上右擊,選擇New->Service Widget->Dynamic Widget(或者靜態也可以)

- 選擇一個模板,我這裏直接選擇Hello World

- 勾選支持的尺寸與默認的尺寸,勾選完後點擊finish創建完成

- 創建好後,會自動打開一個WidgetCard.ets的文件,這個文件是卡片的佈局,我們先不改動這個文件,去找到繼承FormExtensionAbility的類,這個類創建項目的時候會自動創建,其中實現包含了卡片的全部生命週期

- 在創建卡片的生命週期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);
}
// ...
}
- 回到第四步中的WidgetCard.ets,在struct中插入如下代碼,用於接收尺寸信息(第5步的createFormBindingData操作中封裝了保存到本地的動作,可以直接使用LocalStorageProp獲取):
// WidgetCard.ets
// ...
@LocalStorageProp("dimension") dimension: string = '0' // 卡片頁面接收尺寸信息
// ...
- 根據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
}
})
})
}
}
- 效果展示

- 提一嘴,除了在添加的時候可以設置支持的尺寸,在對應模塊下的resources/base/profile/form_config.json下也可以配置

- 至此,本文完結