锁定设备方向 - React Native(Android)

14
我正在使用React Native 0.29并进行Android开发。我正在尝试锁定设备方向,我需要的是将屏幕锁定为竖屏模式。我尝试使用这个仓库https://github.com/yamill/react-native-orientation,但它还不支持RN 0.29。
是否有任何方法可以锁定设备方向?也许有任何使用Android Studio的本地Android hack吗?
6个回答

27

只需在AndroidManifest.xml中的活动中添加android:screenOrientation="portrait"。


如何添加请参见此链接:https://dev59.com/GmUo5IYBdhLWcg3w3ycF - Ibanêz
在React Native项目中,android/app/src/main/AndroidManifest.xml - Thom

3

2017年更新

目前,如果您使用Expo,则可以通过在app.json中添加:

"orientation": "portrait"

一次性为Android和iOS完成它的另一种方法。

{
  "expo": {
    "name": "My app",
    "slug": "my-app",
    "sdkVersion": "21.0.0",
    "privacy": "public",
    "orientation": "portrait"
  }
}

在运行时:

ScreenOrientation.allow()

例子:

ScreenOrientation.allow(ScreenOrientation.Orientation.PORTRAIT);

注意,这仅适用于使用Expo构建的情况,但由于目前(截至2017年)在React Native Blog的官方指南中推荐使用它,因此可能有很多人在使用它,所以值得一提作为另一种有趣的解决方案,而不是黑客攻击特定于Android的XML配置文件。
更多信息:
有关更多信息,请参见: 如何在React Native中禁用旋转?

2
这里有一个针对0.29.2及以上版本的拉取请求: https://github.com/yamill/react-native-orientation/pull/85 如果使用他的版本,它应该能在0.29.2及以上版本中正常工作: https://github.com/youennPennarun/react-native-orientation 步骤如下:
  1. 解开之前安装的链接: rnpm unlink react-native-orientation
  2. rm -rf node_modules/react-native-orientation
  3. 编辑你的package.json,将react-native-orientation的条目编辑为:

    "react-native-orientation": "youennPennarun/react-native-orientation"

  4. npm install
  5. react-native link react-native-orientation
这样就应该可以正常工作了。您可以跟踪PR的进展,并在合并后切换到主要存储库。

0

react-native-orientation - 不再与新版本兼容(我已尝试了0.39.2)。在链接此模块后,我遇到了编译器错误。 据我所知,现在我们应该使用react-native-orientation-listener

npm install --save react-native-orientation-listener
rnpm link


我真的不知道。我在使用这个模块时遇到了奇怪的问题。要么是因为我对React缺乏经验,要么是有bug... http://stackoverflow.com/questions/41407229/react-native-orientation-listener-cannot-read-property-getorientation-of-undef - Sergey Onishchenko

0

您可以使用react-native-orientation-locker

'react-native-orientation'已被弃用。 使用'react-native-orientation-locker'组件,您将能够检测当前方向,并通过以下方式锁定为纵向/横向:

Orientation.lockToPortrait();

Orientation.lockToLandscapeLeft();

甚至可以使用释放锁

Orientation.unlockAllOrientations();

0

步骤:1

npm install git+https://github.com/yamill/react-native-orientation.git --save

步骤2: react-native link 步骤3: 使用以下内容修改MainApplication.java文件:

import com.github.yamill.orientation.OrientationPackage;// import

@Override
protected List getPackages() {
return Arrays.asList(
new MainReactPackage(),
new OrientationPackage() //add this
);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接