0
点赞
收藏
分享

微信扫一扫

HarmonyOS开发之RichEditor组件实现评论编辑功能

随着社交媒体和即时通讯应用的普及,用户对于内容创作的需求日益增长,特别是对于评论、回复等互动形式。为了满足这一需求,HarmonyOS NEXT提供了强大的RichEditor组件,支持图文混排和文本交互式编辑,使得开发者可以轻松构建功能丰富的编辑界面。本文将通过几个具体场景,详细介绍如何利用RichEditor实现评论编辑功能。

场景一:基于文字图片以及@信息的好友评论

实现思路

  1. 添加文字和图片:使用addTextSpanaddImageSpan方法分别添加文字和图片。
  2. 实现@功能:通过addBuilderSpan方法创建一段不可分割的内容,模拟@功能。
  3. 支持手势操作addTextSpanaddImageSpan均支持手势操作,如点击和长按。

核心代码

@Entry
@Component
struct CommentEditor {
  editorController = new RichEditorController();

  @Builder
  At(str: string) {
    Stack() {
      Text('@' + str).fontColor(Color.Blue)
    }
  }

  build() {
    Column() {
      RichEditor({ controller: this.editorController })
        .width('100%')
        .height(100)
        .backgroundColor(Color.Yellow)
        .onReady(() => {
          this.editorController.addImageSpan($r("app.media.icon"), {
            imageStyle: { size: ["100px", "100px"] }
          });
          this.editorController.addTextSpan('男生女生向前冲', {
            style: { fontColor: Color.Blue, fontSize: 30 }
          });
          this.editorController.addBuilderSpan(() => {
            this.At('华为官方客服')
          });
        });

      Button('添加图片').onClick((event: ClickEvent) => {
        this.editorController.addImageSpan($r("app.media.icon"), {
          imageStyle: { size: ["100px", "100px"] }
        });
      });

      Button('添加文字').onClick((event: ClickEvent) => {
        this.editorController.addTextSpan('新的文字', {
          style: { fontColor: Color.Red, fontSize: 20 }
        });
      });
    }
  }
}

场景二:右下角的剩余字数

实现思路

  1. 显示剩余字数:使用overlay属性在RichEditor组件的右下角显示剩余字数。
  2. 限制输入长度:通过aboutToIMEInput回调限制用户输入的字数。

HarmonyOS开发之RichEditor组件实现评论编辑功能_自定义键盘

核心代码

@Entry
@Component
struct MaxLengthEditor {
  @State message: string = '';
  controller: RichEditorController = new RichEditorController();
  @State getContentLength: number = 0;

  build() {
    Column() {
      RichEditor({ controller: this.controller })
        .height(100)
        .borderWidth(1)
        .borderColor(Color.Red)
        .width('100%')
        .overlay(`${this.getContentLength}/20`, {
          align: Alignment.BottomEnd
        })
        .aboutToIMEInput((value: RichEditorInsertValue) => {
          if (this.getContentLength < 20) {
            this.getContentLength += value.insertValue.length;
            return true;
          }
          promptAction.showToast({ message: '已超出内容最大限制.' });
          return false;
        })
        .aboutToDelete((value: RichEditorDeleteValue) => {
          this.getContentLength -= value.length;
          return true;
        });

      Button('输入文字').onClick((event: ClickEvent) => {
        this.controller.addTextSpan('新的文字', {
          style: { fontColor: Color.Blue, fontSize: 20 }
        });
      });
    }
  }
}

场景三:评论中携带所@的用户的附属信息

实现思路

  1. 添加@信息:使用addBuilderSpan方法添加@信息,并绑定点击事件。
  2. 存储和获取附属信息:使用HashMap存储和获取用户的附属信息。

核心代码

@Entry
@Component
struct AtUserInfoEditor {
  controller: RichEditorController = new RichEditorController();

  @Builder
  At(str: string) {
    Stack() {
      Text('@' + str).fontColor(Color.Blue)
    }.onClick(() => {
      const hashMap: HashMap<string, number> = new HashMap();
      hashMap.set("friend1", 123);
      let result = hashMap.get("friend1");
      console.log('result: ' + result);
    })
  }

  build() {
    Column() {
      RichEditor({ controller: this.controller })
        .height(100)
        .borderWidth(1)
        .borderColor(Color.Red)
        .width('100%');

      Button('添加好友1').onClick((event: ClickEvent) => {
        this.controller.addBuilderSpan(() => {
          this.At('好友1')
        });
      });

      Button('添加好友2').onClick((event: ClickEvent) => {
        this.controller.addBuilderSpan(() => {
          this.At('好友2')
        });
      });
    }
  }
}

场景四:文本选择区域发生变化或编辑状态下光标位置发生变化回调

实现思路

  1. 监听光标变化:使用onSelectionChange回调监听光标位置的变化。
  2. 处理光标变化:在回调中处理光标位置变化的逻辑。

HarmonyOS开发之RichEditor组件实现评论编辑功能_RichEditor_02

核心代码

@Entry
@Component
struct CursorChangeEditor {
  @State message: string = '蜡笔小新';
  controller: RichEditorController = new RichEditorController();

  build() {
    Column() {
      RichEditor({ controller: this.controller })
        .defaultFocus(true)
        .padding(0)
        .height(56)
        .width('90%')
        .borderStyle(BorderStyle.Solid)
        .borderColor(Color.Black)
        .borderWidth(1)
        .padding({ left: 10 })
        .onReady(() => {
          this.controller.addTextSpan(this.message, {
            offset: this.controller.getCaretOffset(),
            style: { fontColor: Color.Orange, fontSize: 16 }
          });
          this.controller.setCaretOffset(this.controller.getCaretOffset() + this.message.length);
        })
        .onSelectionChange((value: RichEditorRange) => {
          console.log('光标位置改变了');
          console.log('start: ' + value.start);
          console.log('end: ' + value.end);
        });

      Button('输入文字').onClick((event: ClickEvent) => {
        this.controller.addTextSpan('新的文字', {
          style: { fontColor: Color.Blue, fontSize: 20 }
        });
      });
    }
  }
}

场景五:自由切换系统键盘和自定义键盘

实现思路

  1. 自定义键盘:创建一个自定义键盘组件,支持添加图片和删除内容。
  2. 切换键盘:通过customKeyboard属性控制切换系统键盘和自定义键盘。

核心代码

@Entry
@Component
struct CustomKeyboardEditor {
  @State message: string = 'Hello World';
  controller = new RichEditorController();
  @State showKeyboard: boolean = false;
  private listData: (string | number | Resource)[] = [
    $r('app.media.img'), $r('app.media.img_1'), $r('app.media.img_2'), $r('app.media.img_3'), $r('app.media.img_4'), $r('app.media.img_5'), $r('app.media.img_6'),
    $r('app.media.img'), $r('app.media.img_1'), $r('app.media.img_2'), $r('app.media.img_3'), $r('app.media.img_4'), $r('app.media.img_5'), $r('app.media.img_6'),
    $r('app.media.img'), $r('app.media.img_1'), $r('app.media.img_2'), $r('app.media.img_3'), $r('app.media.img_4'), $r('app.media.img_5'), $r('app.media.img_6'),
    $r('app.media.img'), $r('app.media.img_1'), $r('app.media.img_2'), $r('app.media.img_3'), $r('app.media.img_4'), $r('app.media.img_5'), $r('app.media.img_6'),
    $r('app.media.img'), $r('app.media.img_1'), $r('app.media.img_2'), $r('app.media.img_3'), $r('app.media.img_4'), $r('app.media.img_5'), $r('app.media.img_6'),
  ];

  @Builder
  CustomKeyboardBuilder() {
    Column() {
      Text('自定义表情键盘')
        .fontSize(25)
        .fontWeight(900)
      Grid() {
        ForEach(this.listData, (item: string | number | Resource) => {
          GridItem() {
            if (typeof item !== 'number' && typeof item !== 'string') {
              Image(item)
                .width(30)
                .onClick(() => {
                  this.controller.addImageSpan(item, { imageStyle: { size: ['110px', '110px'] } });
                });
            }
          }
        })
      }.columnsGap(10).rowsGap(10).padding(5)
      Row() {
        Image($r('app.media.img_7'))
          .width(30)
          .onClick(() => {
            this.controller.deleteSpans({ start: this.controller.getCaretOffset() - 1, end: this.controller.getCaretOffset() });
          });
      }.width('100%').justifyContent(FlexAlign.End).margin({ bottom: 40 })
    }.borderColor(Color.Gray).borderWidth(5)
  }

  build() {
    Column() {
      RichEditor({ controller: this.controller })
        .width('100%')
        .height(100)
        .borderWidth(1)
        .borderColor(Color.Black)
        .onReady(() => {
          this.controller.addTextSpan('有序排队');
        })
        .customKeyboard(this.showKeyboard ? this.CustomKeyboardBuilder() : undefined);

      Button('切换系统键盘与自定义键盘').onClick((event: ClickEvent) => {
        this.showKeyboard = !this.showKeyboard;
      });
    }.height('100%')
  }
}

通过以上几个场景的实现,我们可以看到RichEditor组件在HarmonyOS NEXT中提供了非常强大的功能,可以满足多种复杂的编辑需求。

举报

相关推荐

0 条评论