我如何设置它,使应用程序只在纵向模式下运行?我希望在应用程序运行时禁用横向模式。如何通过编程实现呢?


当前回答

对于Xamarin用户:

如果你把你所有的活动扩展到一个BaseActivity,只需添加:

this.RequestedOrientation = ScreenOrientation.Portrait;

这样问题就解决了。如果你想要任何特定的活动在横向覆盖OnActivityCreated。为:

this.Activity.RequestedOrientation = ScreenOrientation.Landscape;

其他回答

适用于任何Android版本

从XML

你可以在manifest.xml文件中为每个活动指定android:screenOrientation="portrait"。不能在应用程序标记上指定此选项。

从Java

另一个选择是通过编程来实现,例如在Activity基类中:

@Override
public void onCreate(Bundle savedInstanceState) {
  setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}

Android 4+ (API 14+)

最后一个选项是使用活动生命周期监听器,这只在Android 4.0 (API 14+)后可用。所有事情都发生在一个自定义Application类中:

@Override
public void onCreate() {
    super.onCreate();  
    registerActivityLifecycleCallbacks(new ActivityLifecycleAdapter() {
        @Override
        public void onActivityCreated(Activity a, Bundle savedInstanceState) {
            a.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    });
}

ActivityLifecycleAdapter只是一个您需要创建的助手类,它将是ActivityLifecycleCallbacks的一个空实现(因此当您只需要其中一个方法时,您不必重写该接口的每个方法)。

你可以在你的manifest文件中设置这个。

android:name=".your launching activity name"
android:screenOrientation="portrait"

你也可以通过在你的类文件中写这样的代码来达到同样的目的:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

好吧, 我试了所有的答案,但在旧版本的安卓系统上都不行。 所以,最终的解决方案是将这段代码添加到setContentView上面的每个活动:

    setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

在config.xml中的<widget>下添加<preference name="orientation" value="portrait" />对我来说很有效。

(其他解决方案要么在我的设备上不起作用,要么在构建过程中被覆盖,要么在构建过程中给出了弃用错误。)

将android:screenOrientation="portrait"添加到AndroidManifest.xml中的活动中。例如:

<activity android:name=".SomeActivity"
    android:label="@string/app_name"
    android:screenOrientation="portrait">