实现效果
代码实现
卡片创建
首先在工程内新建一个Service Widget,可以看到新增了一个EntryFormAbility.ts(卡片生命周期管理文件)、ClickerCard.ets(页面文件,创建时命名为clicker)以及form_config.json(卡片配置文件)。
在预览器中可以看到默认的样子,如下图:
修改样式
删掉默认的UI结构,根据我们的需求设置UI,写法跟普通页面是一样的。
随便加点颜色,让卡片看起来不那么单调:
build() {
Stack() {
Column()
.width('100%').height('100%')
.backdropBlur(5)
.radialGradient({
center: [0, 0],
radius: 30,
repeating: true,
colors: [['#ccf96000', 0.0], ['#faad14', 0.6]]
})
Text('Clicker')
.fontSize(22).fontColor(Color.White)
}
.width('100%').height('100%')
}
现在卡片变成了这样:
增加按钮
移除文字,添加一个按钮,实现发送消息的。这里需要用到卡片的事件能力。
// action类型
readonly ACTION_TYPE: string = 'message';
// 消息
readonly MESSAGE: string = 'click once';
Button(this.TITLE) {
// 按钮使用了一个svg图标
Image($r('app.media.ic_public_home'))
.width(26).height(26).fillColor(Color.White)
}
.padding(10)
.backgroundColor('rgba(255, 255, 255, 0.25)')
.shadow({ radius: 30, color: Color.White })
.onClick(() => {
postCardAction(this, {
"action": this.ACTION_TYPE,
"abilityName": this.ABILITY_NAME,
"params": {
"message": this.MESSAGE
}
});
console.log('clicker', `FormAbility onEvent, action = ${this.ACTION_TYPE}, message: ${this.MESSAGE}`);
})
再来看看我们的卡片:
点击按钮可以在日志里看到打印:
在生命周期回调中,接收消息:
// EntryFormAbility.ts
onFormEvent(formId, message) {
console.log(
'clicker',
`FormAbility onEvent, formId = ${formId}, message: ${JSON.stringify(message)}`);
}
真机运行
点击服务卡片按钮,查看日志:
可以看到服务卡片点击事件的日志和生命周期回调中的日志都已成功打印。
至此,一个简单的带有点击按钮的服务卡片就完成啦。虽然功能很简单,但一个功德木鱼是不是可以以此开始了呢...
完结散花
如发现文章内容有任何问题,请提出您的宝贵意见予以指正,感谢您的阅读。