有人知道如何检测 Nativescript 的方向变化吗?

Does anybody know how to detect orientation change for Nativescript?

我为一个屏幕创建了两个 xml 文件。一个名为 "login-page.port.xml",另一个名为 "login-page.land.xaml"。

有没有办法以编程方式检测应用程序内的方向变化?

谢谢, 凯克斯

是的,有一种方法可以检测应用程序中的方向变化。最简单的方法是在你想要获取方向的页面中;将加载和卸载的事件添加到您的 page.xml 文件中:

<Page loaded="pageLoaded" unloaded="pageUnloaded">

在您的 page.js 文件中;添加这样的代码:

var application=require('application');
exports.pageLoaded = function() {
  application.on(application.orientationChangedEvent, setOrientation);
};

exports.pageUnloaded = function() {
  application.off(application.orientationChangedEvent, setOrientation);
}

function setOrientation(args) {
   // Will console out the new Orientation
   console.log(args.newValue);
}

几个注意事项; 1.你想在进入和退出页面时添加和删除事件监听器;否则监听器是全局的,即使你在另一个页面上,当方向改变时也会继续触发。 2. 您可以向此事件添加多个侦听器,所以如果您不删除侦听器,那么每次重新加载此页面时,您都会将此侦听器的另一个副本添加到组中,因此它会触发多次正如您添加的那样。 3. 在 v1.6.1 的 android 上,它们是方向触发中的错误。 https://github.com/NativeScript/NativeScript/issues/1656(基本上,如果您从横向开始,旋转它不会检测到它。问题是我手动应用到我的代码的补丁)。


现在看你的实际例子;您知道吗,至少从 NativeScript 的版本 1.6.x 开始,它只会加载 XML 当前设置的任何方向;但它不会在您旋转时加载其他方向的 xml。所以,如果你在景观中;进入屏幕然后旋转它仍将使用景观 xml 文件。


综上所述,您可能会认真考虑查看我编写的 nativescript-orientation 插件,该插件简化了屏幕方向的处理,并允许您只有一个 .xml文件,然后通过 css.

更改内容

对于使用

的用户

请参考on method found in the documentation

on(event: "orientationChanged", callback: function, thisArg?: any): any Defined in application/application.d.ts:232 This event is raised the orientation of the current device has changed.

Parameters

event: "orientationChanged"

callback: function

(args: OrientationChangedEventData): void Parameters

args: OrientationChangedEventData

Returns void Optional thisArg: any

Returns any

使用示例:

@Component({
    selector: "Test"
    //templateUrl, styleUrls, etc... 
})
export class TestComponent{
   constructor(){
     on("orientationChanged", this.onOrientationChanged)
   }

   public onOrientationChanged = (evt) => {
      console.log("Orientation has changed !");
      console.log(evt.eventName); // orientationChanged
      console.log(evt.newValue); //landscape or portrait
    };

}