Adding Native widget to layout


#1

Super simple - but no amount of googling is getting me anywhere.

I’m creating a Button widget on android. I want to add it to the NS layout.

        import { android as androidApplication } from "tns-core-modules/application/application";

       ...

        var context = androidApplication.context;
        var button = new android.widget.Button(context);
        button.setText("My Button");
        // Init your component properties here.
        var layout = this.page.getViewById("layout") as LayoutBase;
        layout.addChild(button as any); 

In the HTML

<StackLayout class="form" verticalAlignment="center" id="layout">
....
</StackLayout>

I get the following error

ERROR Error: android.widget.Button{1570e0e VFED…C… …I. 0,0-0,0} is not a valid View instance.

As a note, the documentation I’m relying on (https://docs.nativescript.org/core-concepts/accessing-native-apis-with-javascript#working-with-classes-and-objects-on-android) seems to describe how to create the widget, but not how to add it to the layout.


#2

You can’t add a native widget where add child expect a NativeScript View. To add native widgets you should use place holder.


#3

Additional info: To use place holder with angular (slightly different to the Placeholder docs):

  1. Add the HTML snippet, but with angular syntax
<Placeholder (creatingView)="creatingView($event)"></Placeholder>
  1. Add the method to your component.
    creatingView(args: CreateViewEventData) {
        ...
    }