如何在 Android 中禁用横向模式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/582185/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 02:18:46  来源:igfitidea点击:

How to Disable landscape mode in Android?

androidandroid-manifestandroid-orientation

提问by lostInTransit

How can I disable landscape mode for some of the views in my Android app?

如何为我的 Android 应用程序中的某些视图禁用横向模式?

回答by Yoni Samlan

Add android:screenOrientation="portrait"to the activity in the AndroidManifest.xml. For example:

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

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

EDIT: Since this has become a super-popular answer, I feel very guilty as forcing portrait is rarely the right solution to the problems it's frequently applied to.
The major caveats with forced portrait:

编辑:由于这已成为一个超级流行的答案,我感到非常内疚,因为强制肖像很少是它经常应用于的问题的正确解决方案。
强制肖像的主要警告:

  • This does not absolve you of having to think about activity lifecycle events or properly saving/restoring state. There are plenty of things besides app rotation that can trigger an activity destruction/recreation, including unavoidable things like multitasking. There are no shortcuts; learn to use bundles and retainInstancefragments.
  • Keep in mind that unlike the fairly uniform iPhone experience, there are some devices where portrait is not the clearly popular orientation. When users are on devices with hardware keyboards or game pads a la the Nvidia Shield, on Chromebooks, on foldables, or on Samsung DeX, forcing portrait can make your app experience either limiting or a giant usability hassle. If your app doesn't have a strong UX argument that would lead to a negative experience for supporting other orientations, you should probably not force landscape. I'm talking about things like "this is a cash register app for one specific model of tablet always used in a fixed hardware dock."
  • 这并不能免除您必须考虑活动生命周期事件或正确保存/恢复状态的责任。除了应用程序轮换之外,还有很多事情可以触发活动破坏/娱乐,包括多任务处理等不可避免的事情。没有捷径;学习使用包和retainInstance片段。
  • 请记住,与相当统一的 iPhone 体验不同,在某些设备中,纵向并不是明显流行的方向。当用户使用带有硬件键盘或游戏手柄的设备(如 Nvidia Shield)、Chromebook可折叠设备Samsung DeX 时,强制纵向显示可能会使您的应用体验受到限制或带来巨大的可用性麻烦。如果您的应用程序没有强大的 UX 参数会导致支持其他方向的负面体验,那么您可能不应该强制横向。我在谈论诸如“这是一个收银机应用程序,适用于始终用于固定硬件扩展坞的一种特定型号的平板电脑。”

So most apps should just let the phone sensors, software, and physical configuration make their own decision about how the user wants to interact with your app. A few cases you may still want to think about, though, if you're not happy with the default behavior of sensororientation in your use case:

因此,大多数应用程序应该让手机传感器、软件和物理配置自行决定用户希望如何与您的应用程序交互。但是,如果您对用例中的默​​认sensor方向行为不满意,您可能仍然需要考虑一些情况:

  • If your main concern is accidental orientation changes mid-activity that you think the device's sensors and software won't cope with well (for example, in a tilt-based game) consider supporting landscape and portrait, but using nosensorfor the orientation. This forces landscape on most tablets and portrait on most phones, but I still wouldn't recommend this for most "normal" apps (some users just like to type in the landscape softkeyboard on their phones, and many tablet users read in portrait - and you should let them).
  • If you stillneed to force portrait for some reason, sensorPortraitmay be better than portraitfor Android 2.3+; this allows for upside-down portrait, which is quite common in tablet usage.
  • 如果您主要担心的是在活动过程中意外的方向变化,而您认为设备的传感器和软件无法很好地应对(例如,在基于倾斜的游戏中),请考虑支持横向和纵向,但nosensor用于方向。这会强制大多数平板电脑上的横向和大多数手机上的纵向,但我仍然不建议大多数“普通”应用程序使用此功能(有些用户只是喜欢在手机上输入横向软键盘,而许多平板电脑用户则以纵向阅读 - 并且你应该让他们)。
  • 如果由于某种原因仍然需要强制肖像,sensorPortrait可能比portraitAndroid 2.3+更好;这允许颠倒肖像,这在平板电脑使用中很常见。

回答by Rich

I was not aware of the AndroidManifest.xmlfile switch until reading this post, so in my apps I have used this instead:

AndroidManifest.xml在阅读这篇文章之前,我不知道文件切换,所以在我的应用程序中,我使用了它:

setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);     //  Fixed Portrait orientation

回答by Deepak Swami

Add this android:screenOrientation="portrait"in your manifest file where you declare your activity like this

将此添加android:screenOrientation="portrait"到您的清单文件中,您可以像这样声明您的活动

<activity android:name=".yourActivity"
    ....
    android:screenOrientation="portrait" />

If you want to do using java code try

如果你想使用java代码试试

setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); 

before you call setContentViewmethod for your activity in onCreate().

在您setContentView为您的活动调用方法之前onCreate()

Hope this help and easily understandable for all...

希望这对所有人都有帮助并且易于理解......

回答by Mike Weir

A lot of the answers here are suggesting to use "portrait"in your AndroidManifest.xml file. This might seem like a good solution - but as noted in the documentation, you are singling out devices that may only have landscape. You are also forcing certain devices (that work best in landscape) to go into portrait, not getting the proper orientation.

这里的很多答案都建议"portrait"在您的 AndroidManifest.xml 文件中使用。这似乎是一个很好的解决方案 - 但如文档中所述,您正在挑选可能只有横向的设备。您还强迫某些设备(在横向上效果最好)进入纵向,而没有获得正确的方向。

My suggestion is to use "nosensor"instead. This will leave the device to use its default preferred orientation, will not block any purchases/downloads on Google Play, and will ensure the sensor doesn't mess up your (NDK, in my case) game.

我的建议是"nosensor"改用。这将使设备使用其默认的首选方向,不会阻止在 Google Play 上的任何购买/下载,并确保传感器不会弄乱您的(在我的情况下为 NDK)游戏。

回答by Sunil Chaudhary

Just add Like this Line in Your Manifest

只需在您的清单中添加类似这一行

android:screenOrientation="portrait"

机器人:屏幕方向=“肖像”

<manifest
    package="com.example.speedtest"
    android:versionCode="1"
    android:versionName="1.0" >

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >


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

    </application>

</manifest>   

回答by Stephen

If you want user-settings,

如果你想要用户设置,

then I'd recommend setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

那我推荐 setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

You can change the settings from a settings menu.

您可以从设置菜单更改设置。

I require this because my timers must correspond to what's on the screen, and rotating the screen will destroy the current activity.

我需要这样做是因为我的计时器必须与屏幕上的内容相对应,并且旋转屏幕会破坏当前的活动。

回答by Brinda Rathod

You can do this for your entire application without having to make all your activities extend a common base class.

您可以为整个应用程序执行此操作,而不必让所有活动都扩展一个公共基类。

The trick is first to make sure you include an Application subclass in your project. In its onCreate(), called when your app first starts up, you register an ActivityLifecycleCallbacks object (API level 14+) to receive notifications of activity lifecycle events.

诀窍是首先确保您在项目中包含一个 Application 子类。在您的应用程序首次启动时调用的 onCreate() 中,您注册一个 ActivityLifecycleCallbacks 对象(API 级别 14+)以接收活动生命周期事件的通知。

This gives you the opportunity to execute your own code whenever any activity in your app is started (or stopped, or resumed, or whatever). At this point you can call setRequestedOrientation() on the newly created activity.

这使您有机会在应用程序中的任何活动开始(或停止、恢复或其他任何活动)时执行自己的代码。此时,您可以对新创建的活动调用 setRequestedOrientation()。

And do not forget to add app:name=".MyApp" in your manifest file.

并且不要忘记在清单文件中添加 app:name=".MyApp"。

class MyApp extends Application {

    @Override
    public void onCreate() {
        super.onCreate();  

        // register to be informed of activities starting up
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {

            @Override
            public void onActivityCreated(Activity activity, 
                                          Bundle savedInstanceState) {

                // new activity created; force its orientation to portrait
                activity.setRequestedOrientation(
                    ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            }
            ....
        });
    }
}

回答by Karan Datwani

Use this in onCreate() of the Activity

在 Activity 的 onCreate() 中使用它

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

回答by vuhung3990

You should change android:screenOrientation="sensorPortrait"in AndroidManifest.xml

您应该android:screenOrientation="sensorPortrait"在 AndroidManifest.xml 中更改

回答by Deepak Sharma

Just add this attribute in your activity tag.

只需在您的活动标签中添加此属性。

 android:screenOrientation="portrait"