Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

nativescript

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.

like image 849
Michael Eden Avatar asked Feb 17 '16 18:02

Michael Eden


4 Answers

Use the correct import:

const platform = require("platform")

or if you are using typescriptangular2-nativescript

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.

like image 140
odiaz Avatar answered Jan 07 '23 18:01

odiaz


you can try view.getActualSize().width/height on navigatedTo event. only on this event you can get the actual height/width of a layout/view

you can refer here

like image 20
Sagar1911 Avatar answered Jan 07 '23 19:01

Sagar1911


It is possible to watch for the layoutChanged event of View. It is fired every time the layout process is done incl. view resize

myView.on("layoutChanged", function(){
    console.log("layout change");
});
like image 26
Gabriel Cséfalvay Avatar answered Jan 07 '23 19:01

Gabriel Cséfalvay


When NS fires loaded event for a view, it has not been rendered at this point yet. That's why all your views inside have 0 height and width. You can workaround by waiting for sometime and than try to get the view dimensions. Add this to your loaded function:

var height = 0

function checkIfViewRendered() {
    setTimeout(function() {
        height = view.getMeasuredHeight()
    }, 100)
    if (height === 0) checkIfViewRendered()
    else console.log('rendered height is', height)
}

checkIfViewRendered()

Hope this helps.

like image 28
terreb Avatar answered Jan 07 '23 19:01

terreb