使用TypeScript在NativeScript中创建自定义的Android视图

4

我希望在我的nativescript应用中使用typescript展示原生的Android UI组件,比如按钮或画布。例如,我想使用以下typescript代码扩展一个Android按钮:

//custom.js
export class NativeComponent extends android.widget.Button{
  constructor(context){
      super(context);
      this.setText("test");
  }
}

然后我尝试在XML视图中加载它:

Page xmlns="http://schemas.nativescript.org/tns.xsd" loaded="pageLoaded">
  <StackLayout>
    <Label text="Tap the button" class="title"/>
    <Button text="TAP" tap="{{ tapAction }}" />
    <Label text="{{ message }}" class="message" textWrap="true"/>
    <custom:NativeComponent />
  </StackLayout>  
</Page>

...但是这总是崩溃。关于此的文档非常差/我还没有找到任何信息。


你找到解决方案了吗?@Finkes - Phil
1个回答

3
为了使用自定义控件,您必须添加XML命名空间,以便框架知道从哪里加载文件。因此,您的XML应该如下所示:
<Page xmlns="http://schemas.nativescript.org/tns.xsd" xmlns:custom="./path/to/custom.js" loaded="pageLoaded">
  <StackLayout>
    <Label text="Tap the button" class="title"/>
    <Button text="TAP" tap="{{ tapAction }}" />
    <Label text="{{ message }}" class="message" textWrap="true"/>
    <custom:NativeComponent />
  </StackLayout>  
</Page>

此外,JS代码必须遵循特定的结构,例如您必须拥有一个公共函数_createUI()用于在Android中放置本地组件创建。对于iOS,这是在构造函数中完成的。请查看https://docs.nativescript.org/plugins/ui-plugin.html以获取更多详细信息。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接