
鸿蒙应用开发实战【95】— 实战应用状态批量管理操作本文是「号码助手全栈开发系列」第 95 篇持续更新中…开源社区https://openharmonycrossplatform.csdn.net前言批量操作是提升用户效率的关键功能。号码助手的首页支持多选模式用户可一次性对多个应用进行状态变更换绑 / 注销或删除。本篇讲解选择模式状态管理、批量操作栏 UI 和 DAO 层的批量操作实现。本篇涵盖选择模式selectMode状态机、Swipe 手势切换、批量操作栏BulkActionBar、选中 IDs 管理、批量状态更新batchUpdateStatus、批量删除deleteMany。一、选择模式状态机文件pages/HomePage.etsStateselectMode:booleanfalse// 是否处于选择模式StateselectedIds:number[][]// 选中的应用绑定 id 列表状态转换普通模式 ──长按应用列表──→ 选择模式 选择模式 ──点击取消──→ 普通模式 选择模式 ──执行批量操作──→ 普通模式 选择模式 ──选中 0 项──→ 普通模式自动退出二、进入选择模式2.1 长按触发// AppListItem 组件中BuilderAppListItem(item:AppRow){Column().gesture(LongPressGesture({duration:500}).onAction((){this.enterSelectMode()this.toggleSelection(item.binding.id!)}))}2.2 切换选中状态privatetoggleSelection(id:number):void{constidxthis.selectedIds.indexOf(id)if(idx0){this.selectedIds.splice(idx,1)}else{this.selectedIds.push(id)}// 选中状态变更数组引用触发 State 更新this.selectedIds[...this.selectedIds]// 如果取消选中最后一个自动退出选择模式if(this.selectedIds.length0){this.selectModefalse}}三、批量操作栏BulkActionBar进入选择模式后底部出现批量操作栏┌─────────────────────────────────────────┐ │ 已选中 3 项 换绑 注销 删除 │ └─────────────────────────────────────────┘// 选择模式时的底部操作栏if(this.selectMode){Row(){Text(已选中${this.selectedIds.length}项).fontSize(AppFonts.BODY).fontColor(AppColors.TEXT_2).layoutWeight(1)Text(换绑).onClick(()this.batchRebind())Text(注销).onClick(()this.batchCancel())Text(删除).fontColor(AppColors.DANGER).onClick(()this.batchDelete())}.width(100%).height(56).padding({left:16,right:16}).backgroundColor(AppColors.CARD_B).border({width:{top:1},color:AppColors.LINE})}四、DAO 层批量操作4.1 批量更新状态文件features/data/AppBindingDao.ets/** * 批量更新应用绑定状态 * param ids 要更新的记录 id 列表 * param newStatus 目标状态 */staticasyncbatchUpdateStatus(ids:number[],newStatus:BindingStatus):Promisenumber{try{conststoreAppBindingDao.getStore()constpredicatesnewrelationalStore.RdbPredicates(TABLE)predicates.in(id,ids.map(String))// IN 查询constvalues:relationalStore.ValuesBucket{status:newStatus,updated_at:Date.now()}constaffectedRowsawaitstore.update(values,predicates)hilog.info(0x0000,TAG,batchUpdateStatus: %{public}d 行受影响,affectedRows)returnaffectedRows}catch(e){hilog.error(0x0000,TAG,batchUpdateStatus 失败: %{public}s,JSON.stringify(e))thrownewError(batchUpdateStatus 失败: JSON.stringify(e))}}4.2 批量删除/** * 批量删除应用绑定 * param ids 要删除的记录 id 列表 */staticasyncdeleteMany(ids:number[]):Promisenumber{try{conststoreAppBindingDao.getStore()constpredicatesnewrelationalStore.RdbPredicates(TABLE)predicates.in(id,ids.map(String))constaffectedRowsawaitstore.delete(predicates)hilog.info(0x0000,TAG,deleteMany: %{public}d 行删除,affectedRows)returnaffectedRows}catch(e){hilog.error(0x0000,TAG,deleteMany 失败: %{public}s,JSON.stringify(e))thrownewError(deleteMany 失败: JSON.stringify(e))}}五、批量换绑完整流程privateasyncbatchRebind():Promisevoid{if(this.selectedIds.length0)returntry{// 1. 将所有选中项改为待换绑awaitAppBindingDao.batchUpdateStatus(this.selectedIds,待换绑)// 2. 刷新首页数据awaitthis.loadData()// 3. 退出选择模式this.selectModefalsethis.selectedIds[]promptAction.showToast({message:已将${ids.length}项标记为待换绑})}catch(e){hilog.error(0x0000,TAG,batchRebind failed: %{public}s,JSON.stringify(e))promptAction.showToast({message:批量操作失败请重试})}}六、关键 predicates API批量操作依赖RdbPredicates.in()实现// predicates 链式调用constpredicatesnewrelationalStore.RdbPredicates(app_bindings)predicates.in(id,[1,2,3])// WHERE id IN (1,2,3)// 生成的 SQL// UPDATE app_bindings SET status ?, updated_at ? WHERE id IN (1,2,3)// DELETE FROM app_bindings WHERE id IN (1,2,3)七、UI 层级结构HomePage ├── 标题栏selectMode 为 true 时显示取消按钮 ├── 统计卡片选择模式下半透明 ├── 应用列表带选中态勾选标记 │ └── ForEach → AppListItem │ ├── 普通模式显示状态标签 │ └── 选择模式显示勾选框 ├── 三维筛选面板选择模式下隐藏 └── 批量操作栏仅选择模式下显示选中态 UI 实现// AppListItem 选中样式Column().opacity(rowSelected?0.7:1)// 选中项半透明.border({width:rowSelected?1:0,color:AppColors.PRIMARY,radius:14})八、Swipe 手势切换选择模式除了长按还可以通过横向滑动切换选择模式// SwipeGesture 手势Column().gesture(SwipeGesture({direction:SwipeDirection.Left}).onAction((event:GestureEvent){if(event.offsetX-50){// 左滑超过 50pxthis.enterSelectMode()}}))小结功能实现关键代码适用场景选择模式State selectMode toggleSelection长按触发批量管理选中管理selectedIds 数组 引用替换触发刷新[...this.selectedIds]选中计数的 State 更新批量更新状态AppBindingDao.batchUpdateStatus()predicates.in()标记换绑/注销批量删除AppBindingDao.deleteMany()predicates.in()删除无用绑定操作栏条件渲染if (this.selectMode)换绑/注销/删除三个按钮底部操作栏手势LongPressGesture 500ms长按进入 / 左滑进入触发选择模式如果这篇文章对你有帮助欢迎点赞、收藏⭐、关注你的支持是我持续创作的动力相关资源开源鸿蒙跨平台社区https://openharmonycrossplatform.csdn.netHarmonyOS relationalStore APIhttps://developer.huawei.com/consumer/cn/doc/harmonyos-references/relationalstoreHarmonyOS 官方文档https://developer.huawei.com/consumer/cn/doc/HarmonyOS hilog文档https://developer.huawei.com/consumer/cn/doc/harmonyos-references/hilogHarmonyOS testinghttps://developer.huawei.com/consumer/cn/doc/harmonyos-guides/unit-testHarmonyOS 安全与权限https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/permissions-overview