Tuesday, February 4, 2020

How to to handle app's orientation properly.


The app's "alloy.js" is listening to the "orientationchange" event to re-layout content. The problem with this is that the "orientationchange" event provides the orientation of the "device", not the "app". The native device orientation change event will always occur before the app is rotated by the OS. And some devices will be faster or slower to respond to the device orientation change before rotating the app.
Also note that the "device" orientation and "app" orientation can differ as well. Especially when using split-screen mode on a tablet, because when you hold the tablet "landscape", both of the displayed apps will be in "portrait" form. The attached app code mishandles this case.
What you should be doing is listening to the window's "postlayout" event, fetch the window's width/height, and determine if it is portrait/landscape. This will also handle the split-screen case.

//////////////
var window = Ti.UI.createWindow();
window.addEventListener("postlayout", function() {
 var windowSize = window.size;
 var isPortrait = (windowSize.height >= windowSize.width);
 if (isPortrait) {
  Ti.API.info("### Window is in portrait form.");
 } else {
  Ti.API.info("### Window is in landscape form.");
 }
});
window.open();

//////////////
Note that the use-case for "device" orientation is for fixed orientation apps (ex: portrait-only) that want to rotate the UI manually based on device orientation. Camera apps do this.


I hope this helps.

3 comments: