import Button from "android.widget.Button" import { INativeButtonContext, CreateNativeButtonContext } from "../interface.uts" export class NativeButton { $element : UniNativeViewElement; constructor(element : UniNativeViewElement) { //接收传递过来的UniNativeViewElement this.$element = element; this.bindView(); } button : Button | null = null; bindView() { //通过UniElement.getAndroidActivity()获取android平台activity 用于创建view的上下文 this.button = new Button(this.$element.getAndroidActivity()!); //构建原生view //限制原生Button 文案描述不自动大写 this.button?.setAllCaps(false) //监听原生Button点击事件 this.button?.setOnClickListener(_ => { const detail = { value: "CustomValue" } //构建自定义UniNativeViewEvent返回对象 const event = new UniNativeViewEvent("customClick", detail) //触发原生Button的点击事件 this.$element.dispatchEvent(event) }) //UniNativeViewEvent 绑定 安卓原生view this.$element.bindAndroidView(this.button!); } updateText(text : string) { //更新原生Button 文案描述 this.button?.setText(text) } destroy() { //数据回收 } } class NativeButtonContext implements INativeButtonContext { private element : UniElement | null = null constructor(element : UniElement) { this.element = element } updateText(text : string) { let button = this.element?.getAndroidView() if(null != button){ (button as Button).setText(text) } } } /** * 递归查询 */ function iterateElement(homeElement : UniElement) : UniElement | null { if ("NATIVE-VIEW" == homeElement.nodeName) { return homeElement } for (perChildEle of homeElement.children) { let findEle = iterateElement(perChildEle) if (findEle != null) { return findEle } } return null } export function createNativeButtonContext(id : string, ins : ComponentPublicInstance | null = null) : INativeButtonContext | null { if (ins == null) { const pages = getCurrentPages() if (pages.length > 0) { const page = pages[pages.length - 1] const rootViewElement = page.getElementById(id) if (rootViewElement != null) { /** * 找到了root节点,递归检索目标 native-view */ const nativeViewElement = iterateElement(rootViewElement) if (nativeViewElement != null) { return new NativeButtonContext(nativeViewElement) } } } } else { /** * 尝试迭代遍历 */ if (ins.$el != null) { const nativeViewElement = iterateElement(ins.$el as UniElement) if (nativeViewElement != null) { return new NativeButtonContext(nativeViewElement) } } } return null }