前言“海风日记“的隐私密码页面使用自定义数字键盘实现密码输入通过 4 行 3 列的布局模拟真实键盘。本文将从源码出发深入讲解自定义数字键盘的实现。一、自定义数字键盘private readonly KEY_ROWS: string[][] [ [1, 2, 3], [4, 5, 6], [7, 8, 9], [, 0, del] ] handleKey(key: string) { if (key del) { if (this.password.length 0) { this.password this.password.substring(0, this.password.length - 1) } } else if (key.length 0 this.password.length 6) { this.password key if (this.password.length 6) { setTimeout(() { this.hasPassword true this.isSettingMode false this.password }, 300) } } } Column() { ForEach(this.KEY_ROWS, (row: string[]) { Row() { ForEach(row, (key: string) { Column() { if (key del) { SymbolGlyph($r(sys.symbol.delete_left)).fontSize(20).fontColor([COLOR_TEXT_MAIN]) } else if (key.length 0) { Text(key).fontSize(22).fontColor(COLOR_TEXT_MAIN).fontWeight(FontWeight.Medium) } } .layoutWeight(1).height(64) .backgroundColor(key.length 0 ? COLOR_CARD_BG : COLOR_BG_PAGE) .border({ width: 0.5, color: #EDEDED }) .justifyContent(FlexAlign.Center) .alignItems(HorizontalAlign.Center) .onClick(() this.handleKey(key)) }, (key: string, idx: number) key idx) } .width(100%) }, (row: string[], idx: number) row.join()) } .width(100%)二、6 位密码输入Row({ space: 12 }) { ForEach([0, 1, 2, 3, 4, 5], (i: number) { Column() { if (this.password.length i) { Circle().width(14).height(14).fill(COLOR_PRIMARY) } else { Column().width(1).height(1) } } .width(46).height(56) .backgroundColor(COLOR_CARD_BG).borderRadius(10) .border({ width: this.password.length i ? 2 : 1.5, color: this.password.length i ? COLOR_PRIMARY : (this.password.length i ? COLOR_PRIMARY : #E0E0E0) }) .justifyContent(FlexAlign.Center) .alignItems(HorizontalAlign.Center) }, (i: number) i.toString()) } .margin({ top: 24, bottom: 24 })三、总结本文通过“海风日记“的自定义数字键盘深入讲解了密码输入的实现4×3 键盘布局数字 删除键handleKey 逻辑输入、删除、完成6 位密码圆点输入状态展示自动完成6 位输入后自动确认如果这篇文章对你有帮助欢迎点赞、收藏⭐、关注你的支持是我持续创作的动力相关资源Circle 组件文档SymbolGlyph 文档海风日记项目源码[HarmonyOS 开发者官网](https://atomgit.com/openharmony/docs开源鸿蒙跨平台社区