鸿蒙开发-剪贴板.

2 阅读3分钟

歌词怎么复制分享?HarmonyOS剪贴板与分享功能

如果你对歌词创作感兴趣,可以去鸿蒙应用市场搜一下**「词藻本」**,下载下来体验体验。写好歌词后一键复制到剪贴板,或者分享给朋友。体验完了再回来看这篇文章,你会更清楚剪贴板功能是怎么实现的。


写在前面

大家好,我是一名写了十多年Web前端的老兵。从jQuery时代一路走到React/Vue,Web端的剪贴板操作用navigator.clipboard.writeText()就能搞定。去年开始转战鸿蒙生态,用ArkTS开发App,发现鸿蒙的剪贴板API更系统化。

比如:

  • 复制文本:Web里navigator.clipboard.writeText(text);鸿蒙里用pasteboard.getSystemPasteboard().setData()
  • 读取文本:Web里navigator.clipboard.readText();鸿蒙里用pasteboard.getSystemPasteboard().getData()
  • 分享功能:Web里没有原生分享API;鸿蒙里有@ohos.share系统分享能力。

别担心,接下来这篇文章,我会用"词藻本"的歌词分享功能,带你看看HarmonyOS怎么操作剪贴板和实现分享。


这篇文章聊什么

词藻本的歌词分享功能,核心要解决:

  1. 复制歌词:将歌词文本复制到系统剪贴板
  2. 读取剪贴板:从剪贴板粘贴内容
  3. 系统分享:调用系统分享面板
  4. 格式化输出:歌词格式化后再复制

第一步:实现剪贴板操作

// Web前端同学看这里:Web里用navigator.clipboard
// 鸿蒙里用pasteboard模块,需要异步操作

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

// 复制文本到剪贴板
async function copyToClipboard(text: string): Promise<boolean> {
  try {
    const pasteData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_PLAIN, text);
    const systemPasteboard = pasteboard.getSystemPasteboard();
    await systemPasteboard.setData(pasteData);
    return true;
  } catch (err) {
    console.error(`复制失败: ${err}`);
    return false;
  }
}

// 从剪贴板读取文本
async function readFromClipboard(): Promise<string> {
  try {
    const systemPasteboard = pasteboard.getSystemPasteboard();
    const pasteData = await systemPasteboard.getData();

    if (pasteData.hasType(pasteboard.MIMETYPE_TEXT_PLAIN)) {
      return pasteData.primaryText;
    }
    return '';
  } catch (err) {
    console.error(`读取失败: ${err}`);
    return '';
  }
}

// 清空剪贴板
async function clearClipboard(): Promise<void> {
  try {
    const systemPasteboard = pasteboard.getSystemPasteboard();
    await systemPasteboard.clear();
  } catch (err) {
    console.error(`清空失败: ${err}`);
  }
}

第二步:实现歌词格式化

// Web前端同学看这里:字符串模板和格式化
// 鸿蒙里用法基本一致

// 歌词数据结构
interface LyricDraft {
  id: string;
  title: string;
  content: string;
  rhymeGroup: string;
  mood: string;
  createdAt: string;
}

// 格式化歌词用于分享
function formatLyricForShare(lyric: LyricDraft): string {
  let text = `《${lyric.title}》\n\n`;
  text += lyric.content;
  text += `\n\n---\n`;
  text += `情绪: ${lyric.mood}\n`;
  text += `韵脚: ${lyric.rhymeGroup}\n`;
  text += `创作于: ${lyric.createdAt}\n`;
  text += `\n来自「词藻本」App`;
  return text;
}

// 格式化歌词用于复制(纯文本)
function formatLyricForCopy(lyric: LyricDraft): string {
  return `《${lyric.title}》\n\n${lyric.content}`;
}

第三步:实现分享页面

// Web前端同学看这里:React里我们用状态控制弹窗显示
// 鸿蒙里用@State和条件渲染实现

import { share } from '@kit.ShareKit';

@Entry
@Component
struct ShareLyricPage {
  @State currentLyric: LyricDraft | null = null
  @State showToast: boolean = false
  @State toastMessage: string = ''

  async copyLyric() {
    if (!this.currentLyric) return;

    const text = formatLyricForCopy(this.currentLyric);
    const success = await copyToClipboard(text);

    if (success) {
      this.toastMessage = '已复制到剪贴板';
      this.showToast = true;
      setTimeout(() => {
        this.showToast = false;
      }, 2000);
    }
  }

  async shareLyric() {
    if (!this.currentLyric) return;

    try {
      const text = formatLyricForShare(this.currentLyric);
      await share.shareData({
        summary: text,
        url: ''
      });
    } catch (err) {
      console.error(`分享失败: ${err}`);
    }
  }

  async pasteFromClipboard() {
    const text = await readFromClipboard();
    if (text) {
      // 将剪贴板内容填入编辑器
      console.log(`粘贴内容: ${text}`);
    }
  }

  build() {
    Column() {
      if (this.currentLyric) {
        // 歌词预览
        Text(`《${this.currentLyric.title}》`)
          .fontSize(20)
          .fontWeight(FontWeight.Bold)
          .margin({ bottom: 12 })

        Text(this.currentLyric.content)
          .fontSize(14)
          .lineHeight(22)
          .margin({ bottom: 20 })

        // 操作按钮
        Row() {
          Button('复制歌词')
            .layoutWeight(1)
            .height(48)
            .backgroundColor('#3b82f6')
            .borderRadius(12)
            .onClick(() => this.copyLyric())

          Button('分享')
            .layoutWeight(1)
            .height(48)
            .backgroundColor('#22c55e')
            .borderRadius(12)
            .margin({ left: 12 })
            .onClick(() => this.shareLyric())
        }
        .width('100%')
        .margin({ top: 12 })

        Button('从剪贴板粘贴')
          .width('100%')
          .height(48)
          .backgroundColor('#f3f4f6')
          .fontColor('#374151')
          .borderRadius(12)
          .margin({ top: 12 })
          .onClick(() => this.pasteFromClipboard())
      }

      // Toast提示
      if (this.showToast) {
        Text(this.toastMessage)
          .fontSize(14)
          .fontColor('#ffffff')
          .backgroundColor('#374151')
          .borderRadius(8)
          .padding({ left: 16, right: 16, top: 8, bottom: 8 })
          .position({ x: '50%', y: '80%' })
          .translate({ x: '-50%' })
          .animation({ duration: 200 })
      }
    }
    .padding(16)
  }
}

第四步:常见问题

4.1 剪贴板权限

问题:读取剪贴板失败。

解决:鸿蒙系统对剪贴板读取有安全限制,需要用户主动触发粘贴操作。

4.2 分享内容格式

问题:不同平台对分享内容的格式支持不同。

解决:提供纯文本和富文本两种格式,根据场景选择。


总结

这篇文章围绕"词藻本"的歌词分享功能,讲解了:

剪贴板操作

  • pasteboard API的使用
  • 文本复制和读取
  • 异步操作处理

分享功能

  • 系统分享面板调用
  • 歌词格式化输出
  • Toast提示反馈

如果你对"词藻本"感兴趣,欢迎去鸿蒙应用市场搜索下载体验。