通过@ohos.pasteboard(剪贴板)模块提供的管理系统剪贴板能力,可以为系统复制、粘贴功能提供支持。系统剪贴板支持对文本、HTML、URI、Want、PixelMap等内容的操作。
示例如下:
import { pasteboard } from '@kit.BasicServicesKit';
@Entry
@Component
struct CopyText {
private textContent: string = 'Copy me';
aboutToAppear(): void {
AppStorage.setOrCreate('context', this.getUIContext());
}
build() {
Column() {
Text(this.textContent)
.fontSize(20)
.borderRadius(9)
.borderWidth(1)
.padding({
left: 8,
right: 8
})
.fontColor($r('sys.color.ohos_id_color_text_primary'))
.fontWeight(FontWeight.Medium)
.opacity($r('sys.float.ohos_id_alpha_content_secondary'))
.onClick(() => copyText(this.textContent))
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
.alignSelf(ItemAlign.Center)
}
}
/*
* Copy the text to the system clipboard
* @param text - text
* @returns void
*/
function copyText(text: string) {
const uiContext: UIContext | undefined = AppStorage.get('context');
// Create clipboard content object
const pasteboardData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_PLAIN, text);
// Get system clipboard object
const systemPasteboard = pasteboard.getSystemPasteboard();
systemPasteboard.setData(pasteboardData); // Put data into clipboard
systemPasteboard.getData().then((data) => { // Read clipboard content
if (data) {
uiContext?.getPromptAction().showToast({ message: 'Copy succeeded' });
} else {
uiContext?.getPromptAction().showToast({ message: 'Copy failed' });
}
})
}