• HarmonyOS开发探索:自定义键盘-webview


    场景描述

    在特殊的H5场景下需要应用拉起自定义键盘进行输入。

    场景一:使用jsBridge拉起自定义弹窗写自定义键盘,再通过jsBridge传参实现输入。

    场景二:使用web的同层渲染将原生textInput组件渲染到页面上。

    方案描述

    通过注册一个js代理对象被web的registerJavaScriptProxy方法调用拉起CustomDialog,在CustomDialog上放置一个customkeyboard

    场景一:通过jsBridge拉起自定义弹窗,在自定义弹窗上放置自定义键盘,例如需要输入密码时的安全键盘

    效果图

    cke_23701.gif

    方案

    通过注册一个js代理对象被web的registJavaScriptProxy方法调用拉起CustomDialog,在CustomDialog上放置一个自定义键盘组件,通过在H5上input标签的readonly属性和注册的js方法changeNumbers实现在原生端输入数字传到H5上,他们之间通过@Link装饰器绑定的变量进行传值,所以点击删除输入的内容也是可以在H5上实现的。

    核心代码

    1. 通过javaScriptProxy方法拉起自定义弹窗,在H5上的input标签绑定一个onclick事件,当点击输入框后会调用从原生注册过来的js代理方法openWindow。

      1. <input type="text" name="number_info" readonly onclick="openWindow()" value="" style="width: 500px;height: 100px;font-size:50px;border:1px solid # f00;">
      2. <script>
      3. function openWindow() {
      4. let value = document.getElementsByName("number_info")[0].value;
      5. window.myJsb.openDialog(value)
      6. }
      7. </script>

    2. 当H5上openWindow方法被调用后会通过jsBridge调用以下两个js代理方法打开自定义弹窗。

      1. jsbObject: JsbObject = {
      2. openDialog: (value: string) => {
      3. this.showDialog(this, value);
      4. }
      5. }
      6. showDialog(context: object, value: string) {
      7. // 把自定义弹窗调出来
      8. this.currentData = value;
      9. this.dialogController.open()
      10. }
      11. Web({ src: "resource://rawfile/web_test.html", controller: this.webviewController })
      12. .javaScriptAccess(true)
      13. .javaScriptProxy({
      14. name: "myJsb",
      15. object: this.jsbObject,
      16. methodList: ["openDialog"],
      17. controller: this.webviewController
      18. })
    3. 将自定义键盘放置在自定义弹窗上。

      1. @CustomDialog
      2. struct CustomDialogExample {
      3. @Link currentData: string
      4. dialogControllerTwo: CustomDialogController | null = new CustomDialogController({
      5. builder: CustomDialogExample({ currentData: $currentData }),
      6. alignment: DialogAlignment.Bottom,
      7. offset: { dx: 0, dy: -25 }
      8. })
      9. controller?: CustomDialogController
      10. build() {
      11. Column() {
      12. Button('x').onClick(() => {
      13. // 关闭自定义键盘
      14. if (this.controller != undefined) {
      15. this.controller.close()
      16. }
      17. })
      18. Grid() {
      19. ForEach([1, 2, 3, 4, 5, 6, 7, 8, 9, '*', 0, '删除'], (item: number | string) => {
      20. GridItem() {
      21. Button(item + "")
      22. .width(110).onClick(() => {
      23. if (item == '删除') {
      24. if (this.currentData.length > 0) {
      25. this.currentData = this.currentData.substring(0, this.currentData.length - 1);
      26. }
      27. } else {
      28. this.currentData += item
      29. }
      30. })
      31. }
      32. })
      33. }.maxCount(3).columnsGap(10).rowsGap(10).padding(5)
      34. }.backgroundColor(Color.Gray)
      35. }
      36. }
    4. 在自定义键盘上输入内容的时候会调用onChangeInputValue方法,通过里面的runJavaScript调用H5上的js方法changeNumber传值到H5的输入框中。

      1. onChangeInputValue(stateName: string){
      2. console.log('this.currentData:' + this.currentData)
      3. this.webviewController.runJavaScript('changeNumber("'+ this.currentData +'")')
      4. .then((result) => {
      5. console.log('result: ' + result);
      6. })
      7. }
      8. <<input type="text" name="number_info" readonly onclick="openWindow()" value="" style="width: 500px;height: 100px;font-size:50px;border:1px solid # f00;" />
      9. <script>
      10. function changeNumber(value){
      11. document.getElementsByName("number_info")[0].value = value;
      12. }
      13. </script>

    场景二:通过同层渲染渲染一个原生的自定义键盘

    效果图

    cke_28481.gif

    方案

    整体实现效果为:通过web的同层渲染功能实现将原生TextInput组件渲染到H5需要使用自定义键盘的页面中,这样就可以实现在H5拉起自定义键盘,并且使用它的全部功能。

    核心代码

    1. 创建一个自定义键盘并绑定到原生textInput组件上。

      1. @Component
      2. struct ButtonComponent {
      3. controller1: TextInputController = new TextInputController()
      4. @State inputValue: string = ""
      5. // 自定义键盘组件
      6. @Builder
      7. CustomKeyboardBuilder() {
      8. Column() {
      9. Button('x').onClick(() => {
      10. // 关闭自定义键盘
      11. this.controller1.stopEditing()
      12. })
      13. Grid() {
      14. ForEach([1, 2, 3, 4, 5, 6, 7, 8, 9, '*', 0, '# '], (item: number | string) => {
      15. GridItem() {
      16. Button(item + "")
      17. .width(110).onClick(() => {
      18. this.inputValue += item
      19. })
      20. }
      21. })
      22. }.maxCount(3).columnsGap(10).rowsGap(10).padding(5)
      23. }.backgroundColor(Color.Pink)
      24. }
      25. @ObjectLink params: Params
      26. @State bkColor: Color = Color.Red
      27. @State outSetValueTwo: number = 40
      28. @State outSetValueOne: number = 40
      29. @State tipsValue: number = 40
      30. controller: web_webview.WebviewController = new web_webview.WebviewController();
      31. build() {
      32. Column() {
      33. TextInput({ controller: this.controller1, text: this.inputValue })// 绑定自定义键盘
      34. .customKeyboard(this.CustomKeyboardBuilder()).margin(10).border({ width: 1 })
      35. }
      36. .width(this.params.width)
      37. .height(this.params.height)
      38. }
      39. }
    2. 将原生textInput组件通过web同层渲染功能渲染到H5上的embed标签上。

      1. @Entry
      2. @Component
      3. struct WebIndex {
      4. browserTabController: WebviewController = new webview.WebviewController()
      5. build() {
      6. Column() {
      7. Web({ src: $rawfile("test.html"), controller: this.browserTabController })// 配置同层渲染开关开启。
      8. .enableNativeEmbedMode(true)// 获取embed标签的生命周期变化数据。
      9. .onNativeEmbedLifecycleChange((embed) => {
      10. console.log("NativeEmbed surfaceId" + embed.surfaceId);
      11. // 获取web侧embed元素的id。
      12. const componentId = embed.info?.id?.toString() as string
      13. if (embed.status == NativeEmbedStatus.CREATE) {
      14. console.log("NativeEmbed create" + JSON.stringify(embed.info))
      15. // 创建节点控制器,设置参数并rebuild。
      16. let nodeController = new MyNodeController()
      17. nodeController.setRenderOption({
      18. surfaceId: embed.surfaceId as string,
      19. type: embed.info?.type as string,
      20. renderType: NodeRenderType.RENDER_TYPE_TEXTURE,
      21. embedId: embed.embedId as string,
      22. width: px2vp(embed.info?.width),
      23. height: px2vp(embed.info?.height)
      24. })
      25. nodeController.setDestroy(false);
      26. // 根据web传入的embed的id属性作为key,将nodeController存入map。
      27. this.nodeControllerMap.set(componentId, nodeController)
      28. // 将web传入的embed的id属性存入@State状态数组变量中,用于动态创建nodeContainer节点容器,需要将push动作放在set之后。
      29. this.componentIdArr.push(componentId)
      30. } else if (embed.status == NativeEmbedStatus.UPDATE) {
      31. let nodeController = this.nodeControllerMap.get(componentId)
      32. nodeController?.updateNode({
      33. textOne: 'update',
      34. width: px2vp(embed.info?.width),
      35. height: px2vp(embed.info?.height)
      36. } as ESObject)
      37. } else {
      38. let nodeController = this.nodeControllerMap.get(componentId);
      39. nodeController?.setDestroy(true)
      40. this.nodeControllerMap.clear();
      41. this.componentIdArr.length = 0;
      42. }
      43. })// 获取同层渲染组件触摸事件信息。
      44. .onNativeEmbedGestureEvent((touch) => {
      45. console.log("NativeEmbed onNativeEmbedGestureEvent" + JSON.stringify(touch.touchEvent));
      46. this.componentIdArr.forEach((componentId: string) => {
      47. let nodeController = this.nodeControllerMap.get(componentId)
      48. if (nodeController?.getEmbedId() === touch.embedId) {
      49. let ret = nodeController?.postEvent(touch.touchEvent)
      50. if (ret) {
      51. console.log("onNativeEmbedGestureEvent success " + componentId)
      52. } else {
      53. console.log("onNativeEmbedGestureEvent fail " + componentId)
      54. }
      55. }
      56. })
      57. })
      58. }
      59. }
      60. }
      61. <html>
      62. <head>
      63. <title>同层渲染测试html</title>
      64. <meta name="viewport">
      65. </head>
      66. <body>
      67. <div>
      68. <div id="bodyId">
      69. <embed id="nativeTextInput" type="native/TextInput" width="100%" height="100%" src="test?params1=xxx?"
      70. style="background-color:pink"/>
      71. </div>
      72. </div>
      73. </body>
      74. </html>


    最后

    有很多小伙伴不知道学习哪些鸿蒙开发技术?不知道需要重点掌握哪些鸿蒙应用开发知识点?但是又不知道从哪里下手,而且学习时频繁踩坑,最终浪费大量时间。所以本人整理了一些比较合适的鸿蒙(HarmonyOS NEXT)学习路径和一些资料的整理供小伙伴学习

    点击领取→纯血鸿蒙Next全套最新学习资料(安全链接,放心点击

    希望这一份鸿蒙学习资料能够给大家带来帮助,有需要的小伙伴自行领取,限时开源,先到先得~无套路领取!!

    一、鸿蒙(HarmonyOS NEXT)最新学习路线

    有了路线图,怎么能没有学习资料呢,小编也准备了一份联合鸿蒙官方发布笔记整理收纳的一套系统性的鸿蒙(OpenHarmony )学习手册(共计1236页)与鸿蒙(OpenHarmony )开发入门教学视频,内容包含:(ArkTS、ArkUI开发组件、Stage模型、多端部署、分布式应用开发、音频、视频、WebGL、OpenHarmony多媒体技术、Napi组件、OpenHarmony内核、Harmony南向开发、鸿蒙项目实战等等)鸿蒙(HarmonyOS NEXT)…等技术知识点。

    获取以上完整版高清学习路线,请点击→纯血版全套鸿蒙HarmonyOS学习资料

    二、HarmonyOS Next 最新全套视频教程

    三、《鸿蒙 (OpenHarmony)开发基础到实战手册》

    OpenHarmony北向、南向开发环境搭建

    《鸿蒙开发基础》

    • ArkTS语言
    • 安装DevEco Studio
    • 运用你的第一个ArkTS应用
    • ArkUI声明式UI开发
    • .……

    《鸿蒙开发进阶》

    • Stage模型入门
    • 网络管理
    • 数据管理
    • 电话服务
    • 分布式应用开发
    • 通知与窗口管理
    • 多媒体技术
    • 安全技能
    • 任务管理
    • WebGL
    • 国际化开发
    • 应用测试
    • DFX面向未来设计
    • 鸿蒙系统移植和裁剪定制
    • ……

    《鸿蒙进阶实战》

    • ArkTS实践
    • UIAbility应用
    • 网络案例
    • ……

    四、大厂面试必问面试题

    五、鸿蒙南向开发技术

    六、鸿蒙APP开发必备

    七、鸿蒙生态应用开发白皮书V2.0PDF


    完整鸿蒙HarmonyOS学习资料,请点击→纯血版全套鸿蒙HarmonyOS学习资料

    总结
    总的来说,华为鸿蒙不再兼容安卓,对中年程序员来说是一个挑战,也是一个机会。只有积极应对变化,不断学习和提升自己,他们才能在这个变革的时代中立于不败之地。 

                            

  • 相关阅读:
    系统电容匹配误差和校正布局程序 1994
    Windows 10驱动开发入门(一):环境搭建
    【FME实战教程】002:FME完美实现CAD数据转shp案例教程(以三调土地利用现状数据为例)
    dpdk简单实现
    Unity丨移动相机朝向目标并确定目标在摄像机可视范围内丨摄像机注释模型丨摄像机移动丨不同尺寸模型优化丨
    【C++模拟实现】手撕AVL树
    如何开始自动化员工招聘的五个提示
    如何实现搜索引擎中的拼写纠错功能——思路
    Ubuntu查看系统版本信息
    [开源]MIT开源协议,基于Vue3.x可视化拖拽编辑,页面生成工具
  • 原文地址:https://blog.csdn.net/m0_64422261/article/details/140102438