Bruno Ziiê
Bruno Ziiê

Reputation: 3

NativeScript - How to convert xml layout to native view?

I'm trying to create dialog with a custom layout view and when I try do this:

import app = require('application'); 
import { GridLayout } from 'ui/layouts/grid-layout';

const dialog = new android.app.AlertDialog.Builder(app.android.currentContext);
const layout = new GridLayout();

dialog.setView(layout);

So I got the following error:

Uncaught Error: Cannot convert object to Landroid/view/View;

I tried change to:

dialog.setView(layout.android);

And

dialog.setView(layout.nativeView);

And the dialog is displayed empty.

How I can convert a NativeScript UI Object to a native android View?

Upvotes: 0

Views: 608

Answers (1)

bhavin jalodara
bhavin jalodara

Reputation: 1530

you can't access nativeView or android property of nativescript view without adding it to Visual UI tree. when nativescript view is added to UI tree then it gets valid values for android and nativeView.

so you have to do something like this:

let container= <StackLayout>this.page.getViewById("stackContainer");
let layout = new GridLayout();
let label = new Label();
label.text = "Custom Alert working";
layout.addChild(label)
container.addChild(layout)

now you will have values for android and nativeView properties of GridLayout.

but after that you will not be able to use layout.android or layout.nativeView in setView because it already contains parent. so workaround for this that you remove this view from container's native view.

let nativeView=layout.nativeView;
container.nativeView().removeView(nativeView)
dialog.setView(nativeView).show();

also note that removing child from container will also reset child's android property to null. that's why we are saving reference to nativeView variable.

here is working playground demo is you need help:https://play.nativescript.org/?template=play-ng&id=4610ET

Upvotes: 2

Related Questions