index.uts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. import { Button } from "android.widget"
  2. import { INativeButtonContext, CreateNativeButtonContext } from "../interface.uts"
  3. export class NativeButton {
  4. $element: UniNativeViewElement;
  5. constructor(element : UniNativeViewElement) {
  6. //接收传递过来的UniNativeViewElement
  7. this.$element = element;
  8. this.bindView();
  9. }
  10. button : Button | null = null;
  11. bindView() {
  12. //通过UniElement.getAndroidActivity()获取android平台activity 用于创建view的上下文
  13. this.button = new Button(this.$element.getAndroidActivity()!); //构建原生view
  14. //限制原生Button 文案描述不自动大写
  15. this.button?.setAllCaps(false)
  16. //监听原生Button点击事件
  17. this.button?.setOnClickListener(_ => {
  18. const detail = {}
  19. //构建自定义UniNativeViewEvent返回对象
  20. const event = new UniNativeViewEvent("customClick", detail)
  21. //触发原生Button的点击事件
  22. this.$element.dispatchEvent(event)
  23. })
  24. //UniNativeViewEvent 绑定 安卓原生view
  25. this.$element.bindAndroidView(this.button!);
  26. }
  27. updateText(text : string) {
  28. //更新原生Button 文案描述
  29. this.button?.setText(text)
  30. }
  31. destroy() {
  32. //数据回收
  33. }
  34. }
  35. class NativeButtonContext implements INativeButtonContext {
  36. private button : Button | null = null
  37. constructor(button : Button) {
  38. this.button = button
  39. }
  40. updateText(text : string) {
  41. this.button?.setText(text)
  42. }
  43. }
  44. /**
  45. * 递归查询
  46. */
  47. function iterateElement(homeElement : UniElement) : UniElement | null {
  48. if ("NATIVE-VIEW" == homeElement.nodeName) {
  49. return homeElement
  50. }
  51. for (perChildEle of homeElement.children) {
  52. let findEle = iterateElement(perChildEle)
  53. if (findEle != null) {
  54. return findEle
  55. }
  56. }
  57. return null
  58. }
  59. export function createNativeButtonContext(id : string, ins : ComponentPublicInstance | null = null) : INativeButtonContext | null {
  60. if (ins == null) {
  61. const pages = getCurrentPages()
  62. if (pages.length > 0) {
  63. const page = pages[pages.length - 1]
  64. const rootViewElement = page.getElementById(id)
  65. if (rootViewElement != null) {
  66. /**
  67. * 找到了root节点,递归检索目标 native-view
  68. */
  69. const nativeViewElement = iterateElement(rootViewElement)
  70. if (nativeViewElement != null) {
  71. return new NativeButtonContext(nativeViewElement.getAndroidView()! as Button)
  72. }
  73. }
  74. }
  75. } else {
  76. /**
  77. * 尝试迭代遍历
  78. */
  79. if (ins.$el != null) {
  80. const nativeViewElement = iterateElement(ins.$el as UniElement)
  81. if (nativeViewElement != null) {
  82. return new NativeButtonContext(nativeViewElement.getAndroidView()! as Button)
  83. }
  84. }
  85. }
  86. return null
  87. }