鸿蒙 PC ArkUI 实战:短语库、剪贴板与收藏恢复
框架与适配 · ArkUI 引擎源码
前言
在问题单里补复现步骤时,我希望打几个字就能找到常用回复,看一眼内容,随后复制到工单里。下次进来还要找得到常用句子。这个鸿蒙 PC 上的 ArkUI 应用「片语台」分别实现了搜索、复制正文和收藏恢复。验收时我用同一条「复现步骤」穿过三次操作,这样可以看清复制和保存分别在哪一步生效。
把输入框改成 rep,列表从四条收敛为一条,详情应切到「复现步骤」。点复制之后把剪贴板里的正文粘回搜索框,搜索仍只匹配这条。最后收藏它,结束应用进程,再启动并打开收藏页。只要筛选、详情、粘贴结果或重启后的收藏出现不一致,就可以沿这条操作链查到是哪一步出了问题。
搜索结果与复制对象要一致
界面参考了 Raycast Snippets 的搜索与复制流程。左侧显示匹配列表与分类,右侧留出空间给较长的正文和复制按钮。内容区宽度低于 730 vp 时,详情移到列表下方。搜索、收藏筛选和详情仍使用同一组状态。 Raycast Snippets
每条内置短语有固定的 id、标题、分类和正文。检索先去掉查询两端空白,再统一大小写,匹配标题、分类和正文。当前选中项若被过滤掉,就取第一条可见结果。如果结果为空,页面提示没有匹配项,并隐藏复制与收藏操作。
第一次复跑时遇到过列表已命中「复现步骤」,详情仍显示「评审反馈」的情况。详情原先接收一次计算得到的普通 Builder 参数。改成直接从当前状态计算详情,并在点击按钮时重新读取活动条目后,筛选变化和实际操作指向同一条短语。测试时除了数结果,还核对详情正文和最终粘贴值,避免界面看似更新却复制了旧内容。
把选中的正文送入系统剪贴板
复制时使用 BasicServicesKit 的 pasteboard,把正文封装为 text/plain,再调用系统剪贴板的 setData。等待 Promise 完成后才显示「已复制」,失败则提示可重试。分类和标题帮助查找,写入剪贴板的内容只有正文。应用本身只执行用户点击触发的写入。 华为剪贴板开发指南
验证时把复制结果粘回搜索框。由于搜索包含正文,完整的粘贴值仍会命中同一条短语。对照界面控件文本和 clipboard_written 日志,可以同时确认剪贴板里放了什么,以及应用当时选择了哪一条。
收藏何时算保存完成
Preferences 只保存收藏条目的 id,正文和标题仍从内置短语表读取。用 id 关联的好处是调整展示文案或列表顺序时,原来收藏的项还能找到。读取时拿保存值和当前短语表交叉检查,过时的 id 会被忽略。这个例子以逗号拼接少量固定 id,适合小规模预设列表。
保存分为 put 和 flush 两步。页面等待 flush 返回后才更新星标与收藏计数,保存期间临时禁用收藏按钮,避免连续点击交错。退出再启动时重新打开 Preferences,并读取收藏列表。验证时用 HDC 结束应用进程再启动,检查进程号确实发生变化,随后进入收藏页核对记录。 华为用户首选项指南
模拟器实跑记录

03-pasted.jpeg

05-restored.jpeg

07-narrow-copied.jpeg
在 MateBook Pro 2in1 模拟器(API 24、x86_64)中安装调试 HAP。输入 rep 后,只显示「复现步骤」,详情与它的正文一致。点击复制并使用 Ctrl + V 粘回搜索框,读到的文本与预设正文逐字一致。
收藏「复现步骤」后结束并重启应用。新进程读取到 1 条收藏,切换到收藏页仍能找到刚才那条。将窗口从 1100 vp 缩到约 540 vp,界面改为纵向排列,复制按钮仍可点击并出现成功反馈。以上是模拟器实测记录。
同一条短语走过剪贴板和两次进程
MateBook 14 的真机桌面上,输入 rep 后只剩「复现步骤」,右侧详情显示对应的英文正文。点「复制短语」后清空输入并用 Ctrl+V 粘贴。日志里先后出现 clipboard_written id=repro length=67 和输入长度为 67 时仍然只有 1 条匹配。比较日志中的条目 ID 与右侧详情,可以同时确认复制源与用户选中的句子一致。

MateBook 14 全屏,应用 1.0.1 把 67 字符短语粘回本机搜索框后,仍只匹配「复现步骤」。
收藏这个条目,等保存结束,再退出应用进程。重新打开后日志来自另一个进程,favorites_loaded count=1。切换收藏过滤,看到刚才的条目仍带星标,详情上的操作显示「取消收藏」。在窄窗里列表移到详情上方,复制和取消收藏按钮还能找到。用一个函数调用的成功消息来判断保存会缺最后一步,跨进程读回才能确认 Preferences 的结果已经落盘。
14:48:21.013 clipboard_written id=repro length=67
14:48:21.868 favorites_flushed count=1
14:48:23.300 search_results count=1 length=67
14:48:42.187 favorites_loaded count=1

MateBook 14 全屏,结束进程重启后,窄窗收藏页读回「复现步骤」。
把片语台工程放进鸿蒙电脑版 DevEco Studio
用鸿蒙版 DevEco Studio 打开 ArkUIPhraseLibrary。先到 entry/src/main/ets/PhraseCatalog.ets 对照四条示例数据。每条都提供稳定 ID、标题、分类和正文,repro 是文中复测的那条。修改标题或正文时保持 ID,旧收藏才能关联回同一条。AppScope/app.json5 定义包名 com.aasd23.ugcphraselibrary。本轮从 1.0.0 重建时改为 1.0.1,versionCode 改为 1000001,便于在系统应用信息中核对。
| 场地 | 设备和版本 | 验证内容 |
|---|---|---|
| 本机开发与运行 | HUAWEI MateBook 14,型号 MNTXM-24B,HarmonyOS 7.0.0,软件版本 7.0.0.115(SP11C00E103R12P2patch01),API 26.0.0,aarch64,鸿蒙电脑版 DevEco Studio 26.0.0.220。 | 编辑、编译、生成调试签名和安装 1.0.1,测试窄窗、剪贴板回粘与收藏恢复。 |
| 先前的兼容性验证 | MateBook Pro 2in1,API 24,x86_64,软件版本 6.1.0.125(SP12DEVC00E47R1P3)。 | 核对页面缩窄、搜索详情和重开读回。 |

MateBook 14 真机「关于本机」全屏,账号和序列号已遮盖。

API 24 的 MateBook Pro 2in1 模拟器「关于本机」全屏。
搜索框能直接验收这次剪贴板写入,是因为过滤逻辑把短语正文也纳入匹配。先清空旧查询再粘贴很重要。若保留原来的 rep,粘贴结果可能变成两段拼接,匹配失败就会混淆复制与筛选两道路径。正文粘回后仍只出现一条,也比看到「已复制」提示更容易判断是否取到了正确内容。若应用接入了用户自定义短语,还可以准备两条标题相同但不同正文的样本,检验列表项选择与复制动作是否都指向同一个稳定 ID。

MateBook 14 全屏,鸿蒙电脑版 DevEco Studio 中片语台的本机复测版本 1.0.1。
本机项目目标和最低兼容 API 保持 24。打开 IDE 的终端,进入项目根目录后运行下面两条命令。首次执行时,Hvigor 显示 34 项任务通过、耗时 8 秒 5 毫秒。新项目还需要在「项目结构 → 签名配置」给 default 生成调试签名文件。同步后将运行目标设为「此电脑」,启动后核对 IDE 使用了 entry-default-signed.hap。在系统里核对版本名 1.0.1、版本号 1000001 后,再开始搜索和收藏复测。
ohpm install
hvigorw assembleHap --no-daemon
想对照具体实现,可以按下文的文件顺序找。应用配置决定入口与设备类型。短语检索和收藏读写各放一个文件,只有页面负责把当前选择、剪贴板动作和屏幕布局连起来。这样以后把目录换成自己的数据,也能继续用同一条短语验证整段业务。
应用与模块配置
AppScope/app.json5
{
"app": {
"bundleName": "com.aasd23.ugcphraselibrary",
"vendor": "UGC Lab",
"versionCode": 1000000,
"versionName": "1.0.0",
"icon": "$media:layered_image",
"label": "$string:app_name"
}
}
entry/src/main/module.json5
{
"module": {
"name": "entry",
"type": "entry",
"mainElement": "EntryAbility",
"deviceTypes": ["2in1"],
"deliveryWithInstall": true,
"installationFree": false,
"pages": "$profile:main_pages",
"abilities": [
{
"name": "EntryAbility",
"srcEntry": "./ets/entryability/EntryAbility.ets",
"icon": "$media:layered_image",
"label": "$string:entry_label",
"startWindowIcon": "$media:foreground",
"startWindowBackground": "$color:startup",
"exported": true,
"skills": [{ "entities": ["entity.system.home"], "actions": ["action.system.home"] }]
}
]
}
}
页面入口
entry/src/main/ets/entryability/EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
export default class EntryAbility extends UIAbility {
onWindowStageCreate(stage: window.WindowStage): void {
stage.loadContent('pages/Index').then(() => {
hilog.info(0x0412, 'PhraseDesk', 'page_ready');
}).catch((error: BusinessError) => {
hilog.error(0x0412, 'PhraseDesk', 'page_error code=%{public}d', error.code);
});
}
}
短语目录与搜索
entry/src/main/ets/PhraseCatalog.ets
export interface Phrase {
id: string;
title: string;
category: string;
body: string;
}
export const PHRASES: Phrase[] = [
{ id: 'review', title: '评审反馈', category: '协作',
body: '谢谢这次更新。请补充改动范围和验证结果,方便下一轮评审。' },
{ id: 'repro', title: '复现步骤', category: '调试',
body: 'Repro: Please attach the steps, expected result, and actual result.' },
{ id: 'meeting', title: '会议小结', category: '会议',
body: '本次结论:\n下一步:\n负责人和截止日期:' },
{ id: 'reply', title: '进度回复', category: '沟通',
body: '我已收到,正在核对。确认结果后会在同一处更新进展。' }
];
export function filterPhrases(query: string, onlyFavorites: boolean, favorites: string[]): Phrase[] {
const keyword = query.trim().toLowerCase();
return PHRASES.filter((phrase: Phrase) => {
const text = (phrase.title + '\n' + phrase.category + '\n' + phrase.body).toLowerCase();
return (!onlyFavorites || favorites.includes(phrase.id)) && text.includes(keyword);
});
}
收藏存储
entry/src/main/ets/FavoritesStore.ets
import { common } from '@kit.AbilityKit';
import { preferences } from '@kit.ArkData';
import { PHRASES } from './PhraseCatalog';
const KEY = 'favorite_ids';
export class FavoritesStore {
private readonly storage: preferences.Preferences;
constructor(storage: preferences.Preferences) {
this.storage = storage;
}
static async open(context: common.UIAbilityContext): Promise<FavoritesStore> {
const storage = await preferences.getPreferences(context, { name: 'phrase_library' });
return new FavoritesStore(storage);
}
async load(): Promise<string[]> {
const raw = await this.storage.get(KEY, '');
const ids = typeof raw === 'string' ? raw.split(',') : [];
return PHRASES.filter((item) => ids.includes(item.id)).map((item) => item.id);
}
async save(ids: string[]): Promise<void> {
await this.storage.put(KEY, ids.join(','));
await this.storage.flush();
}
}
搜索、预览与操作页
entry/src/main/ets/pages/Index.ets
import { common } from '@kit.AbilityKit';
import { BusinessError, pasteboard } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { FavoritesStore } from '../FavoritesStore';
import { filterPhrases, Phrase } from '../PhraseCatalog';
const INK = '#16253A';
const SUBTLE = '#526177';
const LINE = '#DBE3EC';
const BLUE = '#235880';
@Entry
@Component
struct Index {
@State private query: string = '';
@State private onlyFavorites: boolean = false;
@State private favoriteIds: string[] = [];
@State private selectedId: string = '';
@State private compact: boolean = false;
@State private status: string = '';
@State private storeReady: boolean = false;
@State private saving: boolean = false;
@State private copying: boolean = false;
private favoritesStore?: FavoritesStore;
private lastWidth: number = 0;
aboutToAppear(): void {
void this.loadFavorites();
}
private async loadFavorites(): Promise<void> {
try {
const context = this.getUIContext().getHostContext() as common.UIAbilityContext;
this.favoritesStore = await FavoritesStore.open(context);
this.favoriteIds = await this.favoritesStore.load();
this.storeReady = true;
hilog.info(0x0412, 'PhraseDesk', 'favorites_loaded count=%{public}d', this.favoriteIds.length);
} catch (error) {
this.status = '收藏读取失败';
hilog.error(0x0412, 'PhraseDesk', 'load_error code=%{public}d', (error as BusinessError).code);
}
}
private results(): Phrase[] {
return filterPhrases(this.query, this.onlyFavorites, this.favoriteIds);
}
private activePhrase(): Phrase | undefined {
const items = this.results();
return items.find((item: Phrase) => item.id === this.selectedId) ?? items[0];
}
private async toggleFavorite(phrase: Phrase): Promise<void> {
const store = this.favoritesStore;
if (!this.storeReady || this.saving || !store) {
return;
}
this.saving = true;
const exists = this.favoriteIds.includes(phrase.id);
const next = exists ? this.favoriteIds.filter((id: string) => id !== phrase.id) :
this.favoriteIds.concat([phrase.id]);
try {
await store.save(next);
this.favoriteIds = next;
this.status = exists ? '已取消收藏' : '已加入收藏';
hilog.info(0x0412, 'PhraseDesk', 'favorites_flushed count=%{public}d', next.length);
} catch (error) {
this.status = '收藏保存失败,可重试';
hilog.error(0x0412, 'PhraseDesk', 'save_error code=%{public}d', (error as BusinessError).code);
} finally {
this.saving = false;
}
}
private async copy(phrase: Phrase): Promise<void> {
if (this.copying) {
return;
}
this.copying = true;
try {
const data = pasteboard.createData(pasteboard.MIMETYPE_TEXT_PLAIN, phrase.body);
await pasteboard.getSystemPasteboard().setData(data);
this.status = '已复制 · ' + phrase.title;
hilog.info(0x0412, 'PhraseDesk', 'clipboard_written id=%{public}s length=%{public}d',
phrase.id, phrase.body.length);
} catch (error) {
this.status = '复制失败,可重试';
hilog.error(0x0412, 'PhraseDesk', 'copy_error code=%{public}d', (error as BusinessError).code);
} finally {
this.copying = false;
}
}
@Builder
private FilterButton(label: string, favoriteOnly: boolean) {
Button(label, { type: ButtonType.Normal })
.id(favoriteOnly ? 'favorites-tab' : 'all-tab')
.height(34).padding({ left: 13, right: 13 }).borderRadius(8)
.fontSize(13).fontWeight(FontWeight.Medium)
.fontColor(this.onlyFavorites === favoriteOnly ? '#FFFFFF' : SUBTLE)
.backgroundColor(this.onlyFavorites === favoriteOnly ? BLUE : '#ECF2F7')
.onClick(() => {
this.onlyFavorites = favoriteOnly;
this.status = '';
})
}
@Builder
private Library() {
Column({ space: 12 }) {
Row({ space: 8 }) {
TextInput({ text: this.query, placeholder: '搜索标题、分类或内容' })
.id('phrase-search').layoutWeight(1).height(41).fontSize(15)
.fontColor(INK).backgroundColor('#EFF4F8').borderRadius(8)
.onChange((value: string) => {
this.query = value;
this.status = '';
hilog.info(0x0412, 'PhraseDesk', 'search_results count=%{public}d length=%{public}d',
this.results().length, value.length);
})
if (this.query.length > 0) {
Button('清空', { type: ButtonType.Normal })
.id('clear-search').height(38).fontSize(13).fontColor(BLUE).backgroundColor('#EDF4FA')
.onClick(() => { this.query = ''; this.status = ''; })
}
}.width('100%')
Row({ space: 7 }) {
this.FilterButton('全部', false)
this.FilterButton('收藏', true)
Blank()
Text(this.results().length + ' 条').fontSize(13).fontColor(SUBTLE)
}.width('100%')
ForEach(this.results(), (item: Phrase) => {
Button({ type: ButtonType.Normal }) {
Row({ space: 9 }) {
Text(item.title).fontSize(16).fontWeight(FontWeight.Medium).fontColor(INK)
Blank()
Text(this.favoriteIds.includes(item.id) ? '★ ' + item.category : item.category)
.fontSize(12).fontColor(BLUE)
}.width('100%')
}
.id('phrase-' + item.id)
.width('100%').height(46).padding({ left: 12, right: 12 }).borderRadius(8)
.border({ width: 1, color: this.activePhrase()?.id === item.id ? '#ACCDDF' : '#E6ECF2' })
.backgroundColor(this.activePhrase()?.id === item.id ? '#DDEFF8' : '#F7F9FB')
.onClick(() => { this.selectedId = item.id; this.status = ''; })
}, (item: Phrase) => item.id)
if (this.results().length === 0) {
Text('没有匹配的短语').fontSize(15).fontColor(SUBTLE).margin({ top: 12, bottom: 10 })
}
}
.alignItems(HorizontalAlign.Start)
.width(this.compact ? '100%' : '43%').padding(17)
.backgroundColor('#FFFFFF').border({ width: 1, color: LINE }).borderRadius(14)
}
@Builder
private Detail() {
Column({ space: 16 }) {
Text(this.activePhrase()?.category ?? '').fontSize(13).fontWeight(FontWeight.Medium).fontColor('#A9D7ED')
Text(this.activePhrase()?.title ?? '').fontSize(30).fontWeight(FontWeight.Bold).fontColor('#F7FBFF')
Text(this.activePhrase()?.body ?? '')
.id('phrase-body').fontSize(19).lineHeight(31).fontColor('#E5EDF5')
.width('100%').padding(15).borderRadius(9).backgroundColor('#263950')
Flex({ wrap: FlexWrap.Wrap, alignItems: ItemAlign.Center }) {
Button('复制短语', { type: ButtonType.Normal })
.id('copy-phrase').fontSize(14).fontWeight(FontWeight.Medium).height(40)
.backgroundColor('#F6CF7D').fontColor('#31240B').borderRadius(9)
.padding({ left: 14, right: 14 }).margin({ right: 9, bottom: 5 })
.enabled(!this.copying).onClick(() => {
const phrase = this.activePhrase();
if (phrase) {
void this.copy(phrase);
}
})
Button(this.favoriteIds.includes(this.activePhrase()?.id ?? '') ? '取消收藏' : '收藏短语',
{ type: ButtonType.Normal })
.id('toggle-favorite').fontSize(14).height(40).backgroundColor('#324861').fontColor('#FFFFFF')
.borderRadius(9).padding({ left: 13, right: 13 }).margin({ bottom: 5 })
.enabled(this.storeReady && !this.saving).onClick(() => {
const phrase = this.activePhrase();
if (phrase) {
void this.toggleFavorite(phrase);
}
})
}.width('100%')
}
.width(this.compact ? '100%' : '55%').padding(23)
.alignItems(HorizontalAlign.Start).backgroundColor('#192B40').borderRadius(14)
}
build() {
Scroll() {
Column({ space: 17 }) {
Text('片语台').fontSize(34).fontWeight(FontWeight.Bold).fontColor(INK)
Text('搜索常用短语,确认内容后复制。').fontSize(15).fontColor(SUBTLE)
if (this.compact) {
this.Library()
if (this.activePhrase()) {
this.Detail()
}
} else {
Row() {
this.Library()
if (this.activePhrase()) {
this.Detail()
}
}.width('100%').alignItems(VerticalAlign.Top).justifyContent(FlexAlign.SpaceBetween)
}
if (this.status) {
Text(this.status).id('operation-status').fontSize(14).fontColor(BLUE)
}
}
.width('100%').constraintSize({ maxWidth: 1060 }).alignItems(HorizontalAlign.Start)
.padding({ top: 23, left: 24, right: 24, bottom: 24 })
}
.width('100%').height('100%').align(Alignment.Top).backgroundColor('#F0F4F8')
.onAreaChange((_, area) => {
const width = Math.round(parseFloat(String(area.width)));
const compact = width < 730;
if (this.lastWidth === 0 || this.compact !== compact) {
hilog.info(0x0412, 'PhraseDesk', 'layout width=%{public}d compact=%{public}s',
width, compact ? 'yes' : 'no');
}
this.compact = compact;
this.lastWidth = width;
})
}
}
FAQ
列表已经命中,详情为什么还显旧条目? 前一次复跑确实遇到过这种情况,触发点是输入查询后原选中的条目被过滤掉。先查搜索结果是否正确,再看详情是否仍使用 Builder 先前取得的普通参数值。把详情改为从当前选中项读取以后,真机输入 rep 能同时更新列表和右侧文案,随后复制日志的 ID 也变成 repro。
可以只用星标验收收藏吗? 星标说明当前页面状态已更新。重开验证要确认应用确实结束了旧进程,再看新进程读出的收藏数和条目 ID。碰到两者不一致时,可以先找 favorites_flushed,再查新进程的 favorites_loaded,最后核对短语目录里是否仍保留同一个 ID。
总结
短语库在鸿蒙电脑上完成源码构建、调试签名及本机安装。实际操作用 67 字符的「复现步骤」串起了搜索、粘贴和收藏恢复。窄窗带来的变化只在布局,收藏记录仍按 ID 读回。将示例改成团队自己的短语模板时,给每条固定 ID,再分别验证复制的全文和新进程读到的收藏,可以避免把界面反馈当成最终结果。
更多推荐




所有评论(0)