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


当前回答

来自Android开发者指南:

"orientation" The screen orientation has changed — the user has rotated the device. Note: If your application targets API level 13 or higher (as declared by the minSdkVersion and targetSdkVersion attributes), then you should also declare the "screenSize" configuration, because it also changes when a device switches between portrait and landscape orientations. "screenSize" The current available screen size has changed. This represents a change in the currently available size, relative to the current aspect ratio, so will change when the user switches between landscape and portrait. However, if your application targets API level 12 or lower, then your activity always handles this configuration change itself (this configuration change does not restart your activity, even when running on an Android 3.2 or higher device). Added in API level 13.

所以,在AndroidManifest.xml文件中,我们可以放:

<activity
            android:name=".activities.role_activity.GeneralViewPagerActivity"
            android:label="@string/title_activity_general_view_pager"
            android:screenOrientation="portrait"
            android:configChanges="orientation|keyboardHidden|screenSize"
            >
        </activity> 

其他回答

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

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

对于Xamarin用户:

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

this.RequestedOrientation = ScreenOrientation.Portrait;

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

this.Activity.RequestedOrientation = ScreenOrientation.Landscape;

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

    setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

在kotlin——>

在你的Extends Application类中使用这个onCreate()…

registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
        override fun onActivityCreated(p0: Activity, p1: Bundle?) {
            p0.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE;
        }

        override fun onActivityStarted(p0: Activity) {
        }

        override fun onActivityResumed(p0: Activity) {
        }

        override fun onActivityPaused(p0: Activity) {
        }

        override fun onActivityStopped(p0: Activity) {
        }

        override fun onActivitySaveInstanceState(p0: Activity, p1: Bundle) {
        }

        override fun onActivityDestroyed(p0: Activity) {
        }
    }

    )}

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

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

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

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);