首先先创建一个项目
在该项目下创建一个卡片服务
在module.json5文件下配置
{"module": {..."extensionAbilities": [{"name": "EntryFormAbility","srcEntry": "./ets/entryformability/EntryFormAbility.ets","label": "$string:EntryFormAbility_label","description": "$string:EntryFormAbility_desc","type": "form","metadata": [{"name": "ohos.extension.form","resource": "$profile:form_config"}]}]}
}
卡片的配置文件form_config.json
{"forms": [{"name": "widget","displayName": "$string:widget_display_name","description": "$string:widget_desc","src": "./ets/widget/pages/WidgetCard.ets","uiSyntax": "arkts","window": {"designWidth": 720,"autoDesignWidth": true},"colorMode": "auto","isDefault": true,"updateEnabled": true,"scheduledUpdateTime": "10:30","updateDuration": 1,"defaultDimension": "2*2","supportDimensions": ["2*2"],"formConfigAbility": "ability://EntryAbility","dataProxyEnabled": false,"isDynamic": true,"transparencyEnabled": false,"metadata": []}]
}
卡片的生命周期
const TAG: string = 'EntryFormAbility';
const DOMAIN_NUMBER: number = 0xFF00;export default class EntryFormAbility extends FormExtensionAbility {onAddForm(want: Want): formBindingData.FormBindingData {hilog.info(DOMAIN_NUMBER, TAG, '[EntryFormAbility] onAddForm');// ...// 使用方创建卡片时触发,提供方需要返回卡片数据绑定类let obj: Record<string, string> = {'title': 'titleOnAddForm','detail': 'detailOnAddForm'};let formData: formBindingData.FormBindingData = formBindingData.createFormBindingData(obj);return formData;}onCastToNormalForm(formId: string): void {// 使用方将临时卡片转换为常态卡片触发,提供方需要做相应的处理hilog.info(DOMAIN_NUMBER, TAG, '[EntryFormAbility] onCastToNormalForm');}onUpdateForm(formId: string): void {// 若卡片支持定时更新/定点更新/卡片使用方主动请求更新功能,则提供方需要重写该方法以支持数据更新hilog.info(DOMAIN_NUMBER, TAG, '[EntryFormAbility] onUpdateForm');let obj: Record<string, string> = {'title': 'titleOnUpdateForm','detail': 'detailOnUpdateForm'};let formData: formBindingData.FormBindingData = formBindingData.createFormBindingData(obj);formProvider.updateForm(formId, formData).catch((error: BusinessError) => {hilog.info(DOMAIN_NUMBER, TAG, '[EntryFormAbility] updateForm, error:' + JSON.stringify(error));});}onChangeFormVisibility(newStatus: Record<string, number>): void {// 使用方发起可见或者不可见通知触发,提供方需要做相应的处理,仅系统应用生效hilog.info(DOMAIN_NUMBER, TAG, '[EntryFormAbility] onChangeFormVisibility');}onFormEvent(formId: string, message: string): void {// 若卡片支持触发事件,则需要重写该方法并实现对事件的触发hilog.info(DOMAIN_NUMBER, TAG, '[EntryFormAbility] onFormEvent');// ...}onRemoveForm(formId: string): void {// 删除卡片实例数据hilog.info(DOMAIN_NUMBER, TAG, '[EntryFormAbility] onRemoveForm');// 删除之前持久化的卡片实例数据// 此接口请根据实际情况实现,具体请参考:FormExtAbility Stage模型卡片实例}onConfigurationUpdate(config: Configuration) {// 当前formExtensionAbility存活时更新系统配置信息时触发的回调。// 需注意:formExtensionAbility创建后10秒内无操作将会被清理。hilog.info(DOMAIN_NUMBER, TAG, '[EntryFormAbility] onConfigurationUpdate:' + JSON.stringify(config));}onAcquireFormState(want: Want) {// 卡片提供方接收查询卡片状态通知接口,默认返回卡片初始状态。return formInfo.FormState.READY;}
}
打开WidgetCard.ets卡片页面
上面的常量都在下面引用,可以直接删掉
@Entry
@Component
struct WidgetCard {build() {Column(){Text('标题').fontSize(18)Button('按钮1').onClick(()=>{console.info('aaa','点击了1')postCardAction(this,{action: 'router',abilityName: 'EntryAbility',params: { targetPage: 'funA' }})})Button('按钮2').onClick(()=>{console.info('aaa','点击了2')postCardAction(this,{action: 'router',abilityName: 'EntryAbility',params: {targetPage: 'funB' }})})}.height('100%').width('100%')}
}
因为 abilityName,拉起的是EntryAblity,要修改一下该生命周期
import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
import { hilog } from '@kit.PerformanceAnalysisKit';const TAG: string = 'EntryAbility';
const DOMAIN_NUMBER: number = 0xFF00;export default class EntryAbility extends UIAbility {private selectPage: string = '';private currentWindowStage: window.WindowStage | null = null;onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {// 获取router事件中传递的targetPage参数hilog.info(DOMAIN_NUMBER, TAG, `Ability onCreate: ${JSON.stringify(want?.parameters)}`);if (want?.parameters?.params) {let params: Record<string, Object> = JSON.parse(want.parameters.params as string);this.selectPage = params.targetPage as string;hilog.info(DOMAIN_NUMBER, TAG, `onCreate selectPage: ${this.selectPage}`);}}// 如果UIAbility已在后台运行,在收到Router事件后会触发onNewWant生命周期回调onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void {hilog.info(DOMAIN_NUMBER, TAG, `Ability onNewWant: ${JSON.stringify(want?.parameters)}`);if (want?.parameters?.params) {let params: Record<string, Object> = JSON.parse(want.parameters.params as string);this.selectPage = params.targetPage as string;hilog.info(DOMAIN_NUMBER, TAG, `onNewWant selectPage: ${this.selectPage}`);}if (this.currentWindowStage !== null) {this.onWindowStageCreate(this.currentWindowStage);}}onWindowStageCreate(windowStage: window.WindowStage): void {// Main window is created, set main page for this abilitylet targetPage: string;// 根据传递的targetPage不同,选择拉起不同的页面switch (this.selectPage) {case 'funA':targetPage = 'pages/Fun1';break;case 'funB':targetPage = 'pages/Fun2';break;default:targetPage = 'pages/Index';}if (this.currentWindowStage === null) {this.currentWindowStage = windowStage;}windowStage.loadContent(targetPage, (err, data) => {if (err.code) {hilog.error(DOMAIN_NUMBER, TAG, 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');return;}hilog.info(DOMAIN_NUMBER, TAG, 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');});}
}
点击那个按钮就跳转那个页面