How to find/watch the dimensions of a view in a NativeScript layout?

Michael Eden picture Michael Eden · Feb 17, 2016 · Viewed 10.7k times · Source

When my layout loads any view inside of it has a width and height of NaN, it also has a getMeasuredHeight() and getMeasuredWidth() of 0.

At some point getMeasuredHeight() and getMeasuredWidth() (after the layout is laid out I guess) receive useful values.

How can I get the dimensions of anything? How can I watch them change?? When will .width and .height ever not be NaN??? Why can't I make a view hover over the entire screen????

So far I've been polling every 100ms and I feel pretty dumb. Please help.

Answer

odiaz picture odiaz · Aug 6, 2016

Use the correct import:

const platform = require("platform")

or if you are using

import {screen} from "platform"
//or import {screen} from "tns-core-modules/platform/platform"

then you can use it depending on your language like this :

Typescript:

screen.mainScreen.widthDIPs //for example : 640
screen.mainScreen.widthPixels
screen.mainScreen.heightDIPs
screen.mainScreen.heightPixels

mainScreen implements the ScreenMetrics interface allowing access to the different screen sizes.

JS:

platform.screen.mainScreen.widthDIPs //for example : 640
platform.screen.mainScreen.widthPixels
platform.screen.mainScreen.heightDIPs
platform.screen.mainScreen.heightPixels

NOTE: this properties are the dimensions of the mobile device screen.