DEV Community

HarmonyOS
HarmonyOS

Posted on

Practical Guide: In-Depth Guide to Clipboard Capabilities in HarmonyOS

Read the original article:Practical Guide: In-Depth Guide to Clipboard Capabilities in HarmonyOS

Contents

  • Preface

  • Feature Overview

  • Development Preparation

    • Required Modules
  • Function Implementation

    • Triggering Copy Function via Button Click
  • Summary

Preface

Hello everyone, I am Ruocheng. This series aims to help developers quickly implement small features during HarmonyOS app development. Note that this series will not provide extensive explanations or complex demonstrations, but developers can directly copy and paste the code to implement the feature. However, permissions that need to be requested should be handled by the developers themselves, as this series will not cover very basic concepts.

Feature Overview

This article explains how to implement the basic text copy feature in HarmonyOS apps. By clicking a button, users can copy text, which can then be pasted anywhere. The clipboard feature is a commonly used basic capability in apps, enhancing user experience and allowing users to transfer text between different apps.

Development Preparation

Required Modules

Before developing the clipboard feature, import the following modules:

import { BusinessError, pasteboard } from '@kit.BasicServicesKit';
import { PromptAction } from '@kit.ArkUI';

  promptAction: PromptAction = this.getUIContext().getPromptAction();
Enter fullscreen mode Exit fullscreen mode

Function Implementation

   // Copy text
    async copyText(txt: string) {
        // Get the system clipboard object
        let text = txt;
        // Create a clipboard content object of plain text type
        let pasteData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_PLAIN, text);
        // Write data to the system clipboard
        let systemPasteboard = pasteboard.getSystemPasteboard();
        await systemPasteboard.setData(pasteData);
        // Read data from the system clipboard
        systemPasteboard.getData().then((data) => {
            let outputData = data;
            // Get the number of records in the clipboard
            let recordCount = outputData.getRecordCount();
            // Get each record from the clipboard data
            for (let i = 0; i < recordCount; i++) {
                let record = outputData.getRecord(i).toPlainText();
                console.info('Get data success, record:' + record);
            }

            this.promptAction.showToast({
                message: "Copy succeeded",
                duration: 2000,

            });
        }).catch((error: BusinessError) => {
            // Handle exception scenarios

            this.promptAction.showToast({
                message: "Copy failed",
                duration: 2000,

            });
        })
    }
Enter fullscreen mode Exit fullscreen mode

The key points in this function implementation are already annotated, so no further detailed explanation is provided.

Triggering Copy Function via Button Click

  // Copy text
                   Column() {

                       Image($r("app.media.copyWord"))
                           .width(24)
                           .height(24)
                       Text('Copy')
                           .fontSize(12)
                           .fontColor('#FFFFFF')
                           .margin({ top: 4 })
                   }
                   .onClick(() => {
                       this.copyText(this.dataList.content)
                   }
                   )
                   .margin({ right: 32 })
Enter fullscreen mode Exit fullscreen mode

In the UI part, clicking the button triggers the copy action. Ensure the parameter passed is plain text.

Summary

During app development, copy-and-paste capability is also quite common. Developers can directly copy the code from this article into their projects to implement text copying. For advanced use cases, feel free to leave a comment, and I will write an advanced guide for clipboard operations. Class dismissed.

Written by Full-stack Developer Ruocheng

Top comments (0)