HarmonyOS 获取当前剪切板数据值?

HarmonyOS 原生剪贴板pasteboard是否无法获取剪切值,详细代码见下图。

阅读 522
1 个回答

请参考示例如下:

运行后,先输入验证码,删除,再点击临时粘贴控件(PasteButton)

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

@Entry
@Component
struct Index {
  @State message: string = '';

  build() {
    Row() {
      Column({ space: 10 }) {
        TextInput({ placeholder: '请输入验证码', text: this.message })
          .onChange((value: string) => {
            this.message = value;
          })
        PasteButton().onClick((event: ClickEvent, result: PasteButtonOnClickResult) => {
          if (PasteButtonOnClickResult.SUCCESS === result) {
            pasteboard.getSystemPasteboard().getData((err: BusinessError, pasteData: pasteboard.PasteData) => {
              if (err) {
                console.error(`Failed to get paste data. Code is ${err.code}, message is ${err.message}`);
                return;
              }
              this.message = pasteData.getPrimaryText();
            });
          }
        })
        Text("复制")
          .onClick(() => {
            //剪贴板数据对应的MIME类型,可以是常量中已定义的类型,也可以是自定义的MIME类型,开发者可自定义此参数值,
            let pasteData: pasteboard.PasteData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_PLAIN, this.message);
            let systemPasteboard: pasteboard.SystemPasteboard = pasteboard.getSystemPasteboard();
            systemPasteboard.setData(pasteData, (err, data) => {
              if (err) {
                console.error('Failed to set PasteData. Cause: ' + err.message);
                return;
              }
              console.info('Succeeded in setting PasteData.');
            });

          })
      }
      .width('100%')
    }
    .height('100%')
  }
}

点击复制我,弹窗复制成功,

退出找个记事本,点击粘贴,显示成功

import pasteboard from '@ohos.pasteboard'
import promptAction from '@ohos.promptAction'

@Entry
@Component
export struct CopyText {
  private textContent: string = "复制我"

  build() {
    Column() {
      Text(this.textContent)
        .fontSize($r("sys.float.ohos_id_text_size_body3"))
        .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))
    }
  }
}

function copyText(text: string) {
  const pasteboardData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_PLAIN, text)
  const systemPasteboard = pasteboard.getSystemPasteboard()
  systemPasteboard.setData(pasteboardData) // 将数据放入剪切板
  systemPasteboard.getData().then((data) => {
    if (data) {
      promptAction.showToast({ message: "复制成功" })
    } else {
      promptAction.showToast({ message: "复制失败" })
    }
  })
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
logo
HarmonyOS
子站问答
访问
宣传栏