如何在 Android 上禁用方向更改?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1512045/
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 03:10:26  来源:igfitidea点击:

How do I disable orientation change on Android?

androidandroid-activityandroid-orientation

提问by Vidar Vestnes

I have an application that I just would like to use in portrait mode, so I have defined android:screenOrientation="portrait" in the manifest XML. This works OK for the HTC Magicphone (and prevents orientation changes on other phones as well).

我有一个我只想在纵向模式下使用的应用程序,所以我在清单 XML 中定义了 android:screenOrientation="portrait"。这适用于HTC Magic手机(也可以防止其他手机的方向更改)。

But I have a problem with the HTC G1phone as I open the hardware QWERTY keyboard(not the virtual keyboard). My activity stays in portrait mode, but it seems to get restarted and loses all its states. This does not happen with the HTC Heroversion.

但是当我打开硬件QWERTY 键盘(不是虚拟键盘)时,HTC G1手机出现问题。我的活动保持纵向模式,但它似乎重新启动并失去了所有状态。HTC Hero版本不会发生这种情况。

My application is quite big, so I don't want it to restart and lose all its states when the keyboard is opened. How can I prevent that?

我的应用程序很大,所以我不希望它在键盘打开时重新启动并丢失所有状态。我怎样才能防止这种情况?

回答by Intrications

Update April 2013: Don't do this. It wasn't a good idea in 2009 when I first answered the question and it really isn't a good idea now. See this answer by hackbod for reasons:

2013 年 4 月更新:不要这样做。2009 年我第一次回答这个问题时,这不是一个好主意,现在它确实不是一个好主意。出于以下原因,请参阅 hackbod 的这个答案:

Avoid reloading activity with asynctask on orientation change in android

避免在android中的方向更改时使用异步任务重新加载活动

Add android:configChanges="keyboardHidden|orientation"to your AndroidManifest.xml. This tells the system what configuration changes you are going to handle yourself - in this case by doing nothing.

添加android:configChanges="keyboardHidden|orientation"到您的 AndroidManifest.xml。这会告诉系统您将自己处理哪些配置更改 - 在这种情况下,什么都不做。

<activity android:name="MainActivity"
     android:screenOrientation="portrait"
     android:configChanges="keyboardHidden|orientation">

See Developer reference configChangesfor more details.

有关 更多详细信息,请参阅开发人员参考configChanges

However, your application can be interrupted at any time, e.g. by a phone call, so you really should add code to save the state of your application when it is paused.

但是,您的应用程序可能随时被中断,例如通过电话,因此您确实应该添加代码以在应用程序暂停时保存应用程序的状态。

Update:As of Android 3.2, you also need to add "screenSize":

更新:从 Android 3.2 开始,您还需要添加“screenSize”:

<activity
    android:name="MainActivity"
    android:screenOrientation="portrait"
    android:configChanges="keyboardHidden|orientation|screenSize">

From Developer guide Handling the Configuration Change Yourself

来自开发人员指南自行处理配置更改

Caution: Beginning with Android 3.2 (API level 13), the "screen size" also changes when the device switches between portrait and landscape orientation. Thus, if you want to prevent runtime restarts due to orientation change when developing for API level 13 or higher (as declared by the minSdkVersion and targetSdkVersion attributes), you must include the "screenSize" value in addition to the "orientation" value. That is, you must declare android:configChanges="orientation|screenSize". 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).

注意:从 Android 3.2(API 级别 13)开始,当设备在纵向和横向之间切换时,“屏幕尺寸”也会发生变化。因此,如果在为 API 级别 13 或更高级别(由 minSdkVersion 和 targetSdkVersion 属性声明)开发时要防止由于方向更改而导致运行时重新启动,则除了“orientation”值之外,还必须包括“screenSize”值。也就是说,您必须声明 android:configChanges="orientation|screenSize". 但是,如果您的应用程序面向 API 级别 12 或更低级别,则您的 Activity 始终会自行处理此配置更改(此配置更改不会重新启动您的 Activity,即使在 Android 3.2 或更高版本的设备上运行时)。

回答by ubershmekel

You need to modify AndroidManifest.xml as Intrications(previously Ashton) mentioned and make sure the activity handles the onConfigurationChanged event as you want it handled. This is how it should look:

您需要作为修改的AndroidManifest.xml Intrications(以前阿什顿)提到,确保活动处理的onConfigurationChanged事件,只要你想它来处理。这是它的外观:

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}

回答by m00sey

I've always found you need both

我一直发现你两者都需要

android:screenOrientation="nosensor" android:configChanges="keyboardHidden|orientation"

回答by Dmitry Zaytsev

As said, set android:configChangesof your Activity (in manifest file) to keyboardHidden|orientationand then:

如上所述,将android:configChanges您的 Activity(在清单文件中)设置为keyboardHidden|orientation

1) Override onConfigurationChanged()

1) 覆盖 onConfigurationChanged()

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    //here you can handle orientation change
}

2) Add this line to your activity's onCreate()

2)将此行添加到您的活动 onCreate()

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

It's better than add same line to onConfigurationChanged, because your app will turn to portrait mode and then back to landscape (it will happen only one time, but it's annoying).

这比在 中添加相同的行要好onConfigurationChanged,因为您的应用程序将转为纵向模式,然后又回到横向模式(只会发生一次,但很烦人)。

Also you can set android:screenOrientation="nosensor"for your activity (in manifest). Butusing this way you're a not able to handle orientation changes at all.

您也可以android:screenOrientation="nosensor"为您的活动设置(在清单中)。但是使用这种方式您根本无法处理方向更改。

回答by Muhammad Aamir Ali

Use this..

用这个..

    android:screenOrientation="portrait"

回答by Numenor

In OnCreate method of your activity use this code:

在您的活动的 OnCreate 方法中使用以下代码:

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

Now your orientation will be set to portrait and will never change.

现在您的方向将设置为纵向并且永远不会改变。

回答by Gil Allen

In the AndroidManifest.xml file, for each activity you want to lock add the last screenOrientationline:

在 AndroidManifest.xml 文件中,为每个要锁定的活动添加最后screenOrientation一行:

android:label="@string/app_name"
android:name=".Login"
android:screenOrientation="portrait" >

Or android:screenOrientation="landscape".

或者android:screenOrientation="landscape"

回答by Jorgesys

In your androidmanifest.xmlfile:

在您的androidmanifest.xml文件中:

   <activity android:name="MainActivity" android:configChanges="keyboardHidden|orientation">

or

或者

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}

回答by PoOk

To lock the screen by code you have to use the actual rotation of the screen (0, 90, 180, 270) and you have to know the natural position of it, in a smartphone the natural position will be portrait and in a tablet, it will be landscape.

要通过代码锁定屏幕,您必须使用屏幕的实际旋转(0、90、180、270),并且您必须知道它的自然位置,在智能手机中,自然位置将是纵向,而在平板电脑中,这将是风景。

Here's the code (lock and unlock methods), it has been tested in some devices (smartphones and tablets) and it works great.

这是代码(锁定和解锁方法),它已经在一些设备(智能手机和平板电脑)上进行了测试,效果很好。

public static void lockScreenOrientation(Activity activity)
{   
    WindowManager windowManager =  (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);   
    Configuration configuration = activity.getResources().getConfiguration();   
    int rotation = windowManager.getDefaultDisplay().getRotation(); 

    // Search for the natural position of the device    
    if(configuration.orientation == Configuration.ORIENTATION_LANDSCAPE &&  
       (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) ||  
       configuration.orientation == Configuration.ORIENTATION_PORTRAIT &&   
       (rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270))   
    {   
        // Natural position is Landscape    
        switch (rotation)   
        {   
            case Surface.ROTATION_0:    
                activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);    
                break;      
            case Surface.ROTATION_90:   
                activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT); 
            break;      
            case Surface.ROTATION_180: 
                activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE); 
                break;          
            case Surface.ROTATION_270: 
                activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); 
                break;
        }
    }
    else
    {
        // Natural position is Portrait
        switch (rotation) 
        {
            case Surface.ROTATION_0: 
                activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); 
            break;   
            case Surface.ROTATION_90: 
                activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); 
            break;   
            case Surface.ROTATION_180: 
                activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT); 
                break;          
            case Surface.ROTATION_270: 
                activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE); 
                break;
        }
    }
}

public static void unlockScreenOrientation(Activity activity)
{
    activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}

回答by Roy Doron

In Visual Studio Xamarin:

在 Visual Studio Xamarin 中:

  1. Add:
  1. 添加:

using Android.Content.PM;to you activity namespace list.

using Android.Content.PM;给你的活动命名空间列表。

  1. Add:
  1. 添加:

[Activity(ScreenOrientation = Android.Content.PM.ScreenOrientation.Portrait)]

[Activity(ScreenOrientation = Android.Content.PM.ScreenOrientation.Portrait)]

as an attribute to you class, like that:

作为你班级的一个属性,就像这样:

[Activity(ScreenOrientation = ScreenOrientation.Portrait)]
public class MainActivity : Activity
{...}