鸿蒙5.0开发进阶:UI框架-富文本(RichEditor)

往期鸿蒙全套实战文章必看:


富文本(RichEditor)

RichEditor是支持图文混排和文本交互式编辑的组件,通常用于响应用户的对于图文混合内容的输入操作,例如可以输入图片的评论区。

创建RichEditor组件

RichEditor通过调用接口来创建,可以创建以下两种类型:

创建不使用属性字符串构建的RichEditor组件

RichEditor(value: RichEditorOptions)

其中RichEditorOptions是富文本组件初始化选项。

controller: RichEditorController = new RichEditorController();
options: RichEditorOptions = { controller: this.controller };

RichEditor(this.options)
.onReady(() => {
this.controller.addTextSpan('创建不使用属性字符串构建的RichEditor组件。', {
style: {
fontColor: Color.Black,
fontSize: 15
}
})
})

创建使用属性字符串构建的RichEditor组件

RichEditor(options: RichEditorStyledStringOptions)

其中RichEditorStyledStringOptions是富文本组件初始化选项。

mutableStyledString: MutableStyledString = new MutableStyledString("创建使用属性字符串构建的RichEditor组件。",
[{
start: 0,
length: 5,
styledKey: StyledStringKey.FONT,
styledValue: this.fontStyle
}]);

controller: RichEditorStyledStringController = new RichEditorStyledStringController();
options: RichEditorStyledStringOptions = {controller: this.controller};

RichEditor(this.options)
.onReady(() => {
this.controller.setStyledString(this.mutableStyledString);
})

设置属性

设置自定义选择菜单

通过bindSelectionMenu设置自定义选择菜单。

其中spanType是菜单的类型,默认值为文字类型;content是菜单的内容;responseType是菜单的响应类型,默认类型为长按;options是菜单的选项,可设置自定义选择菜单弹出或关闭时的回调。

自定义菜单超长时,建议内部嵌套Scroll组件使用,避免键盘被遮挡。

RichEditor(this.options)
.onReady(() => {
this.controller.addTextSpan('组件设置了自定义菜单,长按可触发。', {
style: {
fontColor: Color.Black,
fontSize: 18
}
})
})
.bindSelectionMenu(RichEditorSpanType.TEXT, this.SystemMenu, ResponseType.LongPress, {
onDisappear: () => {
this.sliderShow = false
}
})
.width(300)
.height(300)

@Builder
SystemMenu() {
Column() {
Menu() {
if (this.controller) {
MenuItemGroup() {
MenuItem({
startIcon: this.theme.cutIcon,
content: "剪切",
labelInfo: "Ctrl+X",
})
MenuItem({
startIcon: this.theme.copyIcon,
content: "复制",
labelInfo: "Ctrl+C"
})
MenuItem({
startIcon: this.theme.pasteIcon,
content: "粘贴",
labelInfo: "Ctrl+V"
})
}
}
}
.radius(this.theme.containerBorderRadius)
.clip(true)
.backgroundColor(Color.White)
.width(this.theme.defaultMenuWidth)
}
.width(this.theme.defaultMenuWidth)
}

设置输入框光标、手柄颜色

通过caretColor设置输入框光标、手柄颜色。

RichEditor(this.options)
.onReady(() => {
this.controller.addTextSpan('组件设置了光标手柄颜色。', {
style: {
fontColor: Color.Black,
fontSize: 15
}
})
})
.caretColor(Color.Orange)
.width(300)
.height(300)

设置无输入时的提示文本

通过placeholder设置无输入时的提示文本。

其中value为无输入时的提示文本;style为添加提示文本的字体样式,style缺省时默认跟随主题。

RichEditor(this.options)
.placeholder("此处为提示文本...", {
fontColor: Color.Gray,
font: {
size: 15,
w
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值