ArkUI(eTS)开发问题汇总
问题1.aboutToAppear和onAppear的区别?
aboutToAppear:是被@Component修饰自定义组件的生命周期方法,函数在创建自定义组件的新实例后,在执行其build函数之前执行。
onAppear:是每个组件的属性方法,在该组件显示时触发此回调。
eTS里面object类型有办法更新吗?
lis:Array<object> = [
{
'id': 0,
'name': '计划',
'image': $rawfile('index/ic_public_view_list_filled2.png'),
'number':0
},
this.lis['0'].name = 1
然后用这种方式更新前端不会跟着更新,文档里面看到有,但是不支持object类型,有其他方式解决吗?
“number”最好不要作为属性,因为“number”是字段类型。Object请改为class,示例代码如下:
@Observed export class xxx {
id: number;
name: string;
image: string;
number: number;
constructor(id: number, name: string, image:string,number:number) {
this.id = id;
this.name = name;
this.image = name;
this.number = number;
}
}
lis: Array<xxx> = [{
'id': 0,
'name': '计划',
'image': xxx,
'number': 0
}]
this.lis[0].name='new Name'
问题2.ets 的【TextArea】组件如何做到清空操作?
@State text: string = 'test'
TextArea({ placeholder: this.text })
//...
Button().onClick((value: string) => {
this.text = ''
})
问题3.怎么获取鸿蒙系统的小时制
可以使用DateFormatUtil.is24HourClock方法。
问题4.使用ArkUI开发的App能在安卓设备上安装吗?
不可以。HarmonyOS的应用只能运行在鸿蒙系统里。鸿蒙系统能运行HarmonyOS的应用和安卓应用。但是安卓系统只能运行安卓应用。
问题5.如何实现遮罩效果
使用onTouch实现按下抬起事件,.mask()实现遮罩的效果。代码如下:
@Entry
@Component
struct Index {
@State mask:boolean=false
build() {
Column() {
Image('/comment/bg.jpg')
.mask(this.mask?new Rect({ width: '500px', height: '280px' }).fill(Color.Gray):null)
.width('500px').height('280px')
.onTouch((event: TouchEvent) => {
switch(event.type){
case TouchType.Down:
this.mask=true
break;
case TouchType.Up:
this.mask=false
break;
}
})
}.width('100%').margin({ top: 5 })
}
}
问题6.ets声明式ui开发,怎么获取当前系统时间
在这里,我们将字符串用@state包裹,这样可以监听数据的更新
我们给Text绑定点击时间,然后点击,即可显示当前时间,下面是效果。
@Entry
@Component
struct Index {
@State message: string = 'Hello World'
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold).onClick(()=>{
let date = new Date()
//获取当前时间
// this.message=date.toLocaleString();
//周几
// this.message=date.getUTCDay().toString();
//日期
// this.message=date.getUTCDate().toString();
// //农历月份
// this.message=date.getUTCMonth().toString();
this.message=date.getFullYear() + "年" + (date.getMonth() + 1) + "月" + date.getDate() + "日" + date.getHours() + "时" + date.getMinutes() + "分" + date.getSeconds()+ "秒"
})
}
.width('100%')
}
.height('100%')
}
}
https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ui-js-fa-call-pa-0000001050435961
档上的例子是ArkUI的js版本连接ServiceAbility(注意不是Internal Ability方式)的例子,想依葫芦画瓢调一下eTS的,理论上应该是语法上的差异,但是没有复现效果,各位火眼精金帮看一下是我用错了吗?
ets页面布局(就一个按钮,点击调用ServiceSync函数连接pa并发送数据)
Button('发送数据')
.width(200)
.height(50)
.margin({bottom:10})
.onClick(ServiceSync)复制
export async function ServiceSync(): Promise<void> {
console.log("ServiceSync")
// abilityType: 0-Ability; 1-Internal Ability
const ABILITY_TYPE_EXTERNAL: number = 0
// syncOption(Optional, default sync): 0-Sync; 1-Async
const ACTION_SYNC: number = 0
//请求类型(code)
const ACTION_MESSAGE_CODE_TYPE1: number = 1001
//请求数据
let actionData: Object = {
"firstNum": 1024,
"secondNum": 2048
}
let action: CallAbilityParam
action.bundleName = "com.example.test"
action.abilityName = "com.example.test.ComputeServiceAbility"
action.messageCode = ACTION_MESSAGE_CODE_TYPE1
action.data = actionData
action.abilityType = ABILITY_TYPE_EXTERNAL
action.syncOption = ACTION_SYNC
let result = await FeatureAbility.callAbility(action)
let ret = JSON.parse(result)
if (ret.code == 0) {
console.info('plus result is:' + JSON.stringify(ret.abilityResult))
} else {
console.error('plus error code:' + JSON.stringify(ret.code))
}
}复制
PA端(和官方文档例子相同)
package com.example.test;
// ohos相关接口包
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.rpc.IRemoteBroker;
import ohos.rpc.IRemoteObject;
import ohos.rpc.RemoteObject;
import ohos.rpc.MessageParcel;
import ohos.rpc.MessageOption;
import ohos.utils.zson.ZSONObject;
import java.util.HashMap;
import java.util.Map;
public class ComputeServiceAbility extends Ability {
// 定义日志标签
private static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x00210, "MY_TAG");
private MyRemote remote = new MyRemote();
// FA在请求PA服务时会调用Ability.connectAbility连接PA,连接成功后,需要在onConnect返回一个remote对象,供FA向PA发送消息
@Override
protected IRemoteObject onConnect(Intent intent) {
HiLog.info(LABEL, "onConnect");
super.onConnect(intent);
return remote.asObject();
}
class MyRemote extends RemoteObject implements IRemoteBroker {
private static final int SUCCESS = 0;
private static final int ERROR = 1;
private static final int PLUS = 1001;
MyRemote() {
super("MyService_MyRemote");
}
@Override
public boolean onRemoteRequest(int code, MessageParcel data, MessageParcel reply, MessageOption option) {
HiLog.info(LABEL, "onRemoteRequest:%d|%s" , code , data.readString());
switch (code) {
case PLUS: {
String dataStr = data.readString();
RequestParam param = new RequestParam();
try {
param = ZSONObject.stringToClass(dataStr, RequestParam.class);
} catch (RuntimeException e) {
HiLog.error(LABEL, "convert failed.");
}
// 返回结果当前仅支持String,对于复杂结构可以序列化为ZSON字符串上报
Map<String, Object> result = new HashMap<String, Object>();
result.put("code", SUCCESS);
result.put("abilityResult", param.getFirstNum() + param.getSecondNum());
reply.writeString(ZSONObject.toZSONString(result));
break;
}
default: {
Map<String, Object> result = new HashMap<String, Object>();
result.put("abilityError", ERROR);
reply.writeString(ZSONObject.toZSONString(result));
return false;
}
}
return true;
}
@Override
public IRemoteObject asObject() {
return this;
}
}
}
const ABILITY_TYPE_EXTERNAL = 0;
const ACTION_SYNC = 0;
const ACTION_MESSAGE_CODE_PLUS = 1001;
export default {
plus: async function () {
let data = {
'first': 123,
'second': 234
}
let dataJson:String = JSON.stringify(data)
var action = {
'bundleName': 'com.huawei.myapplication',
'abilityName': 'com.huawei.myapplication.ComputeServiceAbility',
'messageCode': ACTION_MESSAGE_CODE_PLUS,
'abilityType': ABILITY_TYPE_EXTERNAL,
'data': dataJson,
'syncOption': ACTION_SYNC
};
var result = await FeatureAbility.callAbility(action);
var ret = JSON.parse(result);
if (ret.code == 0) {
console.info('plus result is:' + JSON.stringify(ret.abilityResult));
} else {
console.error('plus error code:' + JSON.stringify(ret.code));
}
}
}
找到原因了,之前跟进调试发现callAbility的参数是callAbilityParam,文档里也没有详细定义,想当然以为是个类,就直接实例化对象了
let action: CallAbilityParam复制
后来在gloabl.ets发现这是个ingerface,所以这样用
let result = await FeatureAbility.callAbility({
bundleName: 'com.example.test' ,
abilityName: 'com.example.test.ComputeServiceAbility' ,
messageCode: ACTION_MESSAGE_CODE_TYPE1 ,
data: { firstNum : 1024, secondNum : 2048 },
abilityType: ABILITY_TYPE_EXTERNAL,
syncOption: ACTION_SYNC
})
- 点赞
- 收藏
- 关注作者
评论(0)