HarmonyOS メモアプリの編集機能実装ガイド

本文はApi12に基づいています。

リッチテキストエディタの設定

メモアプリの編集ページでは、RichEditorコンポーネントを使用します。重要なポイントは、value: RichTextConfigというパラメータを通じてスタイルを設定し、最終的な内容を取得できることです。

const editorCtrl = new RichTextController();
const config = { controller: editorCtrl };
new RichTextEditor(config)
    .onLoad(() => {
        this.currentTime = getCurrentTime();
        setInterval(() => {
            this.currentTime = getCurrentTime();
        }, 1000);
    })
    .placeholder("メモを入力...", { color: "#666666" })
    .caretColor(Color.Red)
    .padding(10)
    .marginTop(10)
    .onSelect((selection) => {
        this.startPos = selection.start;
        this.endPos = selection.end;
    })
    .alignment({
        top: { anchor: "header", align: Align.Bottom },
        bottom: { anchor: "footer", align: Align.Top }
    }).marginBottom(80);

スタイル変更の実装

コンテンツのスタイル変更には、初期化パラメータで設定されたリッチテキストコントローラーを使います。具体的には、選択した範囲にスタイルを適用する方法と、新しい内容を入力する前にスタイルを選択する方法があります。

function applyBold() {
    if (this.startPos !== -1 && this.endPos !== -1) {
        editorCtrl.updateSpanStyle({
            start: this.startPos,
            end: this.endPos,
            style: {
                fontWeight: FontWeight.Bold
            }
        });
    }
}
function changeFontSize() {
    if (this.startPos !== -1 && this.endPos !== -1) {
        editorCtrl.updateSpanStyle({
            start: this.startPos,
            end: this.endPos,
            style: {
                fontSize: this.selectedFontSize
            }
        });
    }
}

データ保存の実装

編集が完了したら、内容を保存する必要があります。HarmonyOSの環境では、ohos.data.preferences(ユーザー設定)を利用することが推奨されます。

let memoTitle = this.memoTitle;
let bgColor = this.selectedBgColor;
let id = this.contentId || Date.now();
let spans = JSON.stringify(editorCtrl.getSpans());
let memoBean = new MemoContentBean();

if (memoTitle && spans) {
    memoBean.title = memoTitle;
    memoBean.time = getCurrentTime();
    memoBean.timestamp = Date.now();
    memoBean.id = id;
    memoBean.bgColor = bgColor;
    memoBean.content = spans;

    let summary = "";
    editorCtrl.getSpans().forEach(span => {
        if (summary.length < 30) {
            summary += span.text.trim();
        }
    });
    memoBean.summary = summary;
    let jsonMemo = JSON.stringify(memoBean);
    UserPreferences.getInstance().putSync("memo_" + id, jsonMemo);
}

タグ: HarmonyOS RichTextEditor LocalDataStorage

7月11日 22:15 投稿