1

我开始使用 NativeScript + Angular 2,我想实现一个组件,根据设备方向激活不同的路由。经过大量搜索,我能够让它工作,但我还没有弄清楚如何获得初始设备方向,这听起来应该更容易。

这是我的AppComponent代码。看ngAfterViewInit

import {Component, OnInit, OnDestroy, AfterViewInit} from "@angular/core";
import {Router} from "@angular/router";

import _application = require('application');

@Component({
    selector: "my-app",
    templateUrl: "app.component.html",
})
export class AppComponent implements OnInit, AfterViewInit, OnDestroy {
    constructor(private router: Router) {}

    ngOnInit() {
        _application.on(_application.orientationChangedEvent, this.setOrientation.bind(this));
    }

    ngAfterViewInit() {
        // How do I get the initial orientation here instead of hardcoding to 'portrait'?
        this.setOrientation({newValue: 'portrait'})
    }

    ngOnDestroy() {
        _application.off(_application.orientationChangedEvent, this.setOrientation);
    }

    setOrientation(args) {
        if (args.newValue === 'landscape') {
            this.router.navigate(['/landscape']);
        } else {
            this.router.navigate(['/portrait']);
        }
    }
}
4

3 回答 3

2
private activity:any = application.android.foregroundActivity;
this.activity.getResources().getConfiguration().orientation;
于 2016-10-01T09:15:11.337 回答
1

你可以使用这个插件。为了访问最新版本,您需要每月向维护ProPlugins的开发人员支付订阅费用。

您可以使用以下命令安装它的最后一个免费版本:

npm i nativescript-orientation

这并不能保证它会起作用,尤其是在 {N} 6+ 中。

安装后,您可以获得当前的屏幕方向,如下所示:

const orientation = require("nativescript-orientation");
console.log(orientation.getOrientation());
于 2019-08-10T20:50:29.153 回答
0

虽然没有帮助确定我所知道的初始方向,但您仍然可以获得当前的屏幕尺寸。您可以从核心库中导入屏幕模块。

import { screen } from 'tns-core-modules/platform';

然后在应用程序初始化时通过确定屏幕高度是否大于宽度来确定方向:

this.orientation = screen.mainScreen.heightPixels > screen.mainScreen.widthPixels ? 'portrait' : 'landscape';

编辑:这可能不一致并且没有经过全面测试(这意味着屏幕高度可能并不总是纵向模式下的屏幕高度)。如果是这种情况,在页面加载时,您可以使用相同的策略来测量主要页面元素并比较视图的高度和宽度以确定方向。

于 2020-02-25T03:37:06.860 回答