鸿蒙小计 API9+
功能:将内容粘贴到剪切板
api:ohos.pasteboard
步骤:
1. 使用 pasteboard.createData 方法定义要复制的数据类型
参数1:剪贴板数据对应的MIME类型
参数2:存储的数据
如:const pasteboardData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_PLAIN, text)
2.使用 pasteboard.getSystemPasteboard 方法获取系统剪切板对象
如:const systemPasteboard = pasteboard.getSystemPasteboard()
3.使用第二步创建出来的系统剪切板对象的 setData 方法 将第一步获取的数据写入系统剪贴板
如:systemPasteboard.setData(pasteboardData)
4.利用第二步创建出来的系统剪切板对象的 getData 方法 获取剪切到的数据,再根据回调函数判断是否获取成功
如:
systemPasteboard.getData().then((data) => {
if (data) {
promptAction.showToast({ message: '复制成功' });
} else {
promptAction.showToast({ message: '复制失败' });
}
demo:
1. import { pasteboard } from '@kit.BasicServicesKit';
1. import { promptAction } from '@kit.ArkUI';
1.
1. @Entry
1. @Component
1. struct CopyText {
1. private textContent: string = '复制';
1.
1. build() {
1. Column() {
1. Text(this.textContent)
1. .fontSize(20)
1. .borderRadius(9)
1. .borderWidth(1)
1. .padding({
1. left: 8,
1. right: 8
1. })
1. .fontColor($r('sys.color.ohos_id_color_text_primary'))
1. .fontWeight(FontWeight.Medium)
1. .opacity($r('sys.float.ohos_id_alpha_content_secondary'))
1. .onClick(() => copyText(this.textContent))
1. }
1. .width('100%')
1. .height('100%')
1. .justifyContent(FlexAlign.Center)
1. .alignSelf(ItemAlign.Center)
1. }
1. }
1.
1. function copyText(text: string) {
1. const pasteboardData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_PLAIN, text)
1. const systemPasteboard = pasteboard.getSystemPasteboard()
1. systemPasteboard.setData(pasteboardData)
1. systemPasteboard.getData().then((data) => {
1. if (data) {
1. promptAction.showToast({ message: '复制成功' });
1. } else {
1. promptAction.showToast({ message: '复制失败' });
1. }
1. })
1. }