HarmonyOS鸿蒙Next中文本的AI识别,如何配置自定义的点击回调,比如识别URL后,打开一个自定义页面
HarmonyOS鸿蒙Next中文本的AI识别,如何配置自定义的点击回调,比如识别URL后,打开一个自定义页面
文本的ai识别,比如对于电话号码,网址,邮箱等AI识别,目前可以通过文档中的组件接口:enableDataDetector开启AI识别功能,并通过dataDetectorConfig配置识别出来的样式。不过他们提供的是系统默认回调,如何自定义回调
Text(
'电话号码:' + this.phoneNumber + '\n' +
'链接:' + this.url + '\n' +
'邮箱:' + this.email + '\n' +
'地址:' + this.address
)
.fontSize(16)
.copyOption(CopyOptions.InApp)
.enableDataDetector(this.enableDataDetector)
.dataDetectorConfig({types : this.types, onDetectResultUpdate: (result: string)=>{} })
.textAlign(TextAlign.Center)
.borderWidth(1)
.padding(10)
.width('100%')
但是如果我想要自己配置一个自定义回调,比如点击电话号码,想要跳出一个弹窗,而不是打开一个菜单。这个应该怎么做
更多关于HarmonyOS鸿蒙Next中文本的AI识别,如何配置自定义的点击回调,比如识别URL后,打开一个自定义页面的实战教程也可以访问 https://www.itying.com/category-93-b0.html
目前,想要实现自定义跳转的效果,可以借助自然语言理解的AI服务进行文本识别。如下网址中,有textProcessing.getEntity的用例,可以拿来识别文本:
然后根据您识别的结果,可以为AI实体对应的属性字符串/span配置onClick回调,从而实现自定义跳转之类的功能。
更多关于HarmonyOS鸿蒙Next中文本的AI识别,如何配置自定义的点击回调,比如识别URL后,打开一个自定义页面的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
首先使用AI能力进行文本识别
import { textProcessing, EntityType } from '@kit.NaturalLanguageKit';
import { BusinessError } from '@kit.BasicServicesKit';
async function testEntityRecognition(inputText: string) {
textProcessing.getEntity(inputText, {
entityTypes: [EntityType.NAME]
}).then(result => {
let outputText = formatEntityResult(result);
console.info(outputText);
}).catch(err => {
console.error(`getEntity errorCode: ${err.code} errorMessage: ${err.message}`);
})
}
function formatEntityResult(entities: textProcessing.Entity[]): string {
if (!entities || !entities.length) {
return 'No entities found.';
}
let output = 'Entities:\n';
for (let i = 0; i < entities.length; i++) {
let entity = entities[i];
output += `Entity[${i}]:
oriText: ${entity.text}
charOffset: ${entity.charOffset}
entityType: ${entity.type}
jsonObject: ${entity.jsonObject}
`;
}
return output;
}
@Entry
@Component
struct Page {
build() {
Column(){
Button('Start').onClick(() => {
// 测试实体识别
let inputText = 'test for nlp getEntity. www.baidu.com Mary, Bob and Mike.';
testEntityRecognition(inputText);
})
}
}
}
基于识别结果,通过属性字符串或者span的onClick来实现自定义回调
// xxx.ets
import promptAction from '@ohos.promptAction';
@Entry
@Component
struct styled_string_demo2 {
scroll: Scroller = new Scroller();
fontStyleAttr1: TextStyle = new TextStyle({ fontColor: Color.Blue });
clickGestureAttr: GestureStyle = new GestureStyle({
onClick: () => {
promptAction.showToast({ message: 'clickGestureAttr object trigger click event' })
this.backgroundColor1 = Color.Yellow
}
})
gestureStyleAttr: GestureStyle = new GestureStyle({
onClick: () => {
promptAction.showToast({ message: 'gestureStyleAttr object trigger click event' })
this.backgroundColor1 = Color.Green
},
onLongPress: () => {
promptAction.showToast({ message: 'gestureStyleAttr object trigger long press event' })
this.backgroundColor1 = Color.Orange
}
});
// 创建事件的对象mutableStyledString3
mutableStyledString3: MutableStyledString = new MutableStyledString("hello world", [{
start: 0,
length: 5,
styledKey: StyledStringKey.GESTURE,
styledValue: this.clickGestureAttr
},
{
start: 0,
length: 5,
styledKey: StyledStringKey.FONT,
styledValue: this.fontStyleAttr1
},
{
start: 6,
length: 5,
styledKey: StyledStringKey.GESTURE,
styledValue: this.gestureStyleAttr
},
{
start: 6,
length: 5,
styledKey: StyledStringKey.FONT,
styledValue: new TextStyle({ fontColor: Color.Pink })
}]);
@State fontColor1: ResourceColor = Color.Red;
@State backgroundColor1: ResourceColor | undefined = undefined;
controller3: TextController = new TextController();
async onPageShow() {
this.controller3.setStyledString(this.mutableStyledString3)
}
build() {
Column() {
Scroll(this.scroll) {
Column({ space: 30 }) {
Button("响应属性字符串事件改变背景色").backgroundColor(this.backgroundColor1).width('80%')
// 包含事件的属性字符串
Text(undefined, { controller: this.controller3 }).fontSize(30)
.copyOption(CopyOptions.InApp)
.draggable(true)
.clip(true)
}.width('100%')
}
.expandSafeArea([SafeAreaType.KEYBOARD])
.scrollable(ScrollDirection.Vertical)
.scrollBar(BarState.On)
.scrollBarColor(Color.Gray)
.scrollBarWidth(10)
.edgeEffect(EdgeEffect.None)
}
.width('100%')
}
}
在HarmonyOS鸿蒙Next中,配置自定义的点击回调可以通过TextRecognizer
的setOnResultListener
方法实现。首先,使用TextRecognizer
进行文本识别,然后在OnResultListener
中处理识别结果。当识别到URL时,可以通过Intent
启动自定义页面。具体代码如下:
let textRecognizer = text.createTextRecognizer();
textRecognizer.setOnResultListener((result) => {
if (result.type === 'URL') {
let intent = { bundleName: 'com.example.custom', abilityName: 'CustomPage' };
featureAbility.startAbility(intent);
}
});
在HarmonyOS Next中,可以通过dataDetectorConfig
的onDetectResultUpdate
回调来实现自定义点击行为。具体实现如下:
- 首先在Text组件中配置dataDetectorConfig,设置onDetectResultUpdate回调:
Text('...')
.enableDataDetector(true)
.dataDetectorConfig({
types: this.types,
onDetectResultUpdate: (result: string) => {
// 这里处理识别结果
this.handleDetectedResult(result);
}
})
- 实现自定义处理函数:
private handleDetectedResult(result: string) {
// 判断识别类型
if (result.startsWith('tel:')) {
// 电话号码处理
this.showCustomDialog(result.substring(4));
} else if (result.startsWith('http')) {
// URL处理
this.navigateToCustomPage(result);
}
// 其他类型处理...
}
private showCustomDialog(phoneNumber: string) {
// 实现自定义弹窗逻辑
AlertDialog.show({
message: `是否拨打 ${phoneNumber}?`,
buttons: [
{
text: '取消',
action: () => {}
},
{
text: '拨打',
action: () => {
// 调用拨号功能
call.makeCall({ phoneNumber });
}
}
]
});
}
private navigateToCustomPage(url: string) {
// 自定义页面跳转逻辑
router.pushUrl({
url: 'pages/CustomWebPage',
params: { url }
});
}
通过这种方式,你可以完全控制识别内容的点击行为,替换系统默认的回调逻辑。注意要处理好不同类型的识别结果(电话、URL、邮箱等),并根据业务需求实现相应的自定义逻辑。