用来显示或者提示一些基本信息,或进行一些基本操作,不能使用重逻辑
新建:1、在ets目录上右击;2、选择Service Widget;3、Dynamic Widget
其中Static Widget,只能做静态页面,不能做数据交互
Dynamic Widget可以做动态数据,及事件处理
在entry的model.json5中,
"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"
}
]
}
]
就是的ability,在这个ability上,就是卡片
在EntryFormAbility中,最主要的方法:onAddForm(),就是做主要的逻辑处理
在Resources / base / profile / 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",
"isDynamic": true,
"isDefault": true,
"updateEnabled": false,
"scheduledUpdateTime": "10:30",
"updateDuration": 1,
"defaultDimension": "2*2",
"supportDimensions": [
"2*2",
"2*4"
]
}
]
}
卡片可以选择2*2和2*4
作用:展示数据、唤起应用;不支持包、不支持网络请求;
在应用的model.json5中,加入权限
'requestPermissions': [{
"name": 'ohos.permission.KEEP_BACKGROUND_RUNNING'
}],
WidgetCard.ets
@Entry
@Component
struct WidgetCard {
@State num: number = 0
build() {
Row() {
Column() {
Button(this.num + '++').onClick(() => {
this.num++
postCardAction(this, {
action: 'call',
abilityName: 'EntryAbility',
params:{
method:'updataNum',
num:this.num
}
});
})
}.width('100%')
}
.height('100%')
.onClick(() => {
postCardAction(this, {
action: 'router', //跳转事件
abilityName: 'EntryAbility',
});
})
}
}
应用的界面:
import { authentication } from '@kit.AccountKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { promptAction } from '@kit.ArkUI';
@Entry
@Component
struct Index {
@State message: string = 'Hello World';
@StorageLink('num')
num:number=0
build() {
RelativeContainer() {
Text(this.message+this.num)
}
.height('100%')
.width('100%')
}
}
EntryAbility.ets
import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { window } from '@kit.ArkUI';
import { rpc } from '@kit.IPCKit';
class Params implements rpc.Parcelable{
marshalling(dataOut: rpc.MessageSequence): boolean {
return true
}
unmarshalling(dataIn: rpc.MessageSequence): boolean {
return true
}
}
class CaraParam{
num:number=0
}
export default class EntryAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
this.callee.on('updataNum',(data)=>{
let res=JSON.parse(data.readString())as CaraParam
AppStorage.setOrCreate('num',res.num)
return new Params()
})
}
//销毁监听
onDestroy(): void {
this.callee.off('updataNum')
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy');
}