How can I disable landscape mode in Android?
Asked Answered
W

32

1059

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

Whiteness answered 24/2, 2009 at 15:29 Comment(1)
Are you essentially trying to disable the auto-rotate feature. Try setting your preferred orientation in your portrait views? http://code.google.com/android/reference/android/R.styleable.html#AndroidManifestActivity_screenOrientationMurtagh
T
1819

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

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

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 retainInstance fragments.
  • 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."

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 sensor orientation in your use case:

  • 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 nosensor for 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 still need to force portrait for some reason, sensorPortrait may be better than portrait for Android 2.3 (Gingerbread) and later; this allows for upside-down portrait, which is quite common in tablet usage.
Tavish answered 24/2, 2009 at 17:4 Comment(15)
It is possible to do it for the entire app. Check this out https://mcmap.net/q/54237/-how-to-set-entire-application-in-portrait-mode-onlyExorcist
I noticed that there's another portrait: sensorPortait. What's the difference between sensorPortait and portrait?Mother
If you read Google's docs: "Portrait orientation, but can be either normal or reverse portrait based on the device sensor. Added in API level 9." So - that is - "portrait, right side up or upside down, Android 2.3+ only."Tavish
As I noted in my answer below - to get around several issues, "nosensor" is likely a better option.Tune
@Quentamia You should add that to your MainActivity and every other activity will follow the same rule.Tman
@PhoenixX_2 "nosensor" is reasonable in situations where your primary concern is really just accidental orientation changes mid-usage; in most circumstances if you're supporting both landscape and portrait layouts (which you have to if you're set up for "nosensor"), most apps are better off not forcing an orientation at all. I'll update my answer to note that, though.Tavish
I don't know which activity name use as I am developing an Ionic App an I didn't edit AndroidManifest.xml What is the name that I should use to lock camera (video) to landscape? You can see my AndroidManifest hereDuleba
Even Facebook app doesn't support landscape mode. Also the Home screen doesn't.Sibell
I have to say I disagree. Not all experiences are compatible with landscape mode on phones, so you should let the UX decide, not the sensors. This isn't the case on tablets though.Soup
@RenzoTissoni I should qualify this that in the 10 years since I wrote this answer (and the 4 years since I updated it!) phone devices with "natural" landscape orientations (eg with hard keyboards) have become basically extinct, Android on tablets has proven to be more or less DOA anyways, and apps like Snapchat have shown there's a real appetite for "pure portrait" phone-only experiences. So that's to say: I agree with you when the UX dictates it. in 2019, though, you do need to think about Chromebooks, foldables (maybe) and things like DEX if you care about those experiences, though!Tavish
@RenzoTissoni I totally agree with you. Since this Answer became the most popular ,Yoni felt the necessity to throw his forced opinion there . I worked on nearly 10+ apps and none of them are still targeted to the tablets at least. Most of these apps have 1M-10M+ active installs now without even supporting landscape mode. It always depends on the app and the product and never the OS!Enisle
Another factor for using portrait only are special phones with additional buttons such as push to talk or SOS/Alert that become harder to reach in landcape mode. sensorPortrait makes more sense there and was a great tip.Stites
Android studio is complaining with an "error" if I try setting the screenOrientation to anything other than unspecified or fullSensor, because otherwise the application can't provide a great user experience. D'oh! But it does compile tough.Tabby
what if all activities...? is there any 1 code for all?Antony
bro @peter you edited every hell answer that exist on stackoverflow.Slump
A
120

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

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); // Fixed portrait orientation
Anhanhalt answered 18/10, 2010 at 14:53 Comment(3)
this can make your activity jump on first load if the device is not in the specified orientation.Ait
I was using this method, I was calling it in OnCreate then I would read data from some asset files. If I would start the app with device in landscape orientation it would rotate but this would result in erroneously reading those initialization assets, for some weird reason (maybe should have wait for the rotation to finish some how). Using the xml alternative didn't cause this issue.Hurd
That may be an issue with the start up sequence for Android programs. You could try moving the setRequestedOrientation() to onResume()???Anhanhalt
O
53

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

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

If you want to do it using Java code, try:

setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

before you call setContentView method for your activity in onCreate().

Outbid answered 27/9, 2012 at 9:47 Comment(0)
T
32

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.

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.

Tune answered 21/8, 2013 at 14:41 Comment(2)
Since many are up-voting this, I'd like to point out that I've since gone with other answers suggesting "portrait" as certain obscure devices do in fact respond unpredictably when wanting to implement in-app screen rotation, which became a requirement later on for me. I also doubt any apps with "portrait" would get blocked by any Google Play setup.Tune
Google Play does in fact filter out portrait-only apps on landscape-only devices, see the note on this page: developer.android.com/guide/topics/manifest/… ("the value you declare enables filtering by services such as Google Play")Undue
K
22

If you want to disable Landscape mode for your Android app (or a single activity) all you need to do is add:

android:screenOrientation="portrait" to the activity tag in AndroidManifest.xml file.

Like:

<activity 
    android:name="YourActivityName"
    android:icon="@drawable/ic_launcher"
    android:label="Your App Name"
    android:screenOrientation="portrait">

Another way: A programmatic approach.

If you want to do this programmatically, i.e., using Java code. You can do so by adding the below code in the Java class of the activity that you don't want to be displayed in landscape mode.

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Kinshasa answered 16/3, 2015 at 5:25 Comment(2)
Since so many answers give advice that contradict the good advice of @Phoenix and @Yoni, I think a good bottom line is to reiterate what they suggest: android:screenOrientation="nosensor">Xanthine
@Xanthine Yes .If you want to cope with tablet devices then you should use the nosensor value instead portraitKinshasa
A
16

Just add this line in your Manifest:

android:screenOrientation="portrait"

Like:

<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>
Arianna answered 5/2, 2015 at 9:30 Comment(0)
B
15

If you want user-settings, then I'd recommend 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.

Bravery answered 10/2, 2012 at 4:46 Comment(0)
K
13

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.

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.

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

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);
            }
            ....
        });
    }
}
Kat answered 5/4, 2018 at 9:28 Comment(0)
P
8

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

Pastille answered 3/1, 2014 at 6:4 Comment(1)
Change to what?Uni
S
8

Use this in onCreate() of the Activity

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Syrian answered 6/5, 2015 at 9:59 Comment(0)
P
7

Just add this attribute in your activity tag.

 android:screenOrientation="portrait"
Phineas answered 1/10, 2013 at 7:0 Comment(1)
Why is it so simple, given the previous answers? E.g., does it depend on the Android version?Uni
R
7

Add android:screenOrientation="portrait" to the activity you want to disable landscape mode in.

Resonant answered 26/1, 2014 at 9:30 Comment(0)
P
7

If you don't want to go through the hassle of adding orientation in each manifest entry of activity better, create a BaseActivity class (inherits 'Activity' or 'AppCompatActivity') which will be inherited by every activity of your application instead of 'Activity' or 'AppCompatActivity' and just add the following piece of code in your BaseActivity:

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    // rest of your code......
}
Pressman answered 22/4, 2017 at 17:51 Comment(1)
Implementation inheritance?Uni
B
7

Put it into your manifest.

<activity
    android:name=".MainActivity"
    android:label="@string/app_name"
    android:screenOrientation="sensorPortrait" />

The orientation will be portrait, but if the user's phone is upside down, it shows the correct way as well. (So your screen will rotate 180 degrees.)


The system ignores this attribute if the activity is running in multi-window mode.

More: https://developer.android.com/guide/topics/manifest/activity-element

Burnard answered 20/3, 2020 at 14:9 Comment(3)
Re "this attribute": What attribute? What does it refer to?Uni
"this attribute" refers to the "screenOreintation" attributeBurnard
I added this as well as android:resizeableActivity="false" but upside down still doesn't work...Partial
K
6

How to change orientation in some of the view

Instead of locking orientation of the entire activity, you can use this class to dynamically lock orientation from any of your view pragmatically:

Make your view Landscape

OrientationUtils.lockOrientationLandscape(mActivity);

Make your view Portrait

OrientationUtils.lockOrientationPortrait(mActivity);

Unlock Orientation

OrientationUtils.unlockOrientation(mActivity);

Orientation Util Class

import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Build;
import android.view.Surface;
import android.view.WindowManager;

/*  * This class is used to lock orientation of android app in nay android devices
 */

public class OrientationUtils {
    private OrientationUtils() {
    }

    /** Locks the device window in landscape mode. */
    public static void lockOrientationLandscape(Activity activity) {
        activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
    }

    /** Locks the device window in portrait mode. */
    public static void lockOrientationPortrait(Activity activity) {
        activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

    /** Locks the device window in actual screen mode. */
    public static void lockOrientation(Activity activity) {
        final int orientation = activity.getResources().getConfiguration().orientation;
        final int rotation = ((WindowManager) activity.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay()
                .getRotation();

        // Copied from Android docs, since we don't have these values in Froyo
        // 2.2
        int SCREEN_ORIENTATION_REVERSE_LANDSCAPE = 8;
        int SCREEN_ORIENTATION_REVERSE_PORTRAIT = 9;

        // Build.VERSION.SDK_INT <= Build.VERSION_CODES.FROYO
        if (!(Build.VERSION.SDK_INT <= Build.VERSION_CODES.FROYO)) {
            SCREEN_ORIENTATION_REVERSE_LANDSCAPE = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
            SCREEN_ORIENTATION_REVERSE_PORTRAIT = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
        }

        if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_90) {
            if (orientation == Configuration.ORIENTATION_PORTRAIT) {
                activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            } else if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
                activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            }
        } else if (rotation == Surface.ROTATION_180 || rotation == Surface.ROTATION_270) {
            if (orientation == Configuration.ORIENTATION_PORTRAIT) {
                activity.setRequestedOrientation(SCREEN_ORIENTATION_REVERSE_PORTRAIT);
            } else if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
                activity.setRequestedOrientation(SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
            }
        }
    }

    /** Unlocks the device window in user defined screen mode. */
    public static void unlockOrientation(Activity activity) {
        activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER);
    }

}
Kopple answered 28/4, 2016 at 6:24 Comment(1)
Re "pragmatically": Do you mean "programmatically" (not a rhetorical question)?Uni
O
5

Use:

android:configChanges="keyboardHidden|orientation"
android:screenOrientation="portrait" 
Ossuary answered 14/5, 2012 at 16:42 Comment(1)
An explanation would be in order. E.g., what is the idea/gist? How is it better/different from the previous answers?Uni
D
5

You must set the orientation of each activity.

<activity
    android:name="com.example.SplashScreen2"
    android:label="@string/app_name"
    android:screenOrientation="portrait"
    android:theme="@android:style/Theme.Black.NoTitleBar" >
</activity>
<activity
    android:name="com.example.Registration"
    android:label="@string/app_name"
    android:screenOrientation="portrait"
    android:theme="@android:style/Theme.Black.NoTitleBar" >
</activity>
<activity
    android:name="com.example.Verification"
    android:label="@string/app_name"
    android:screenOrientation="portrait"
    android:theme="@android:style/Theme.Black.NoTitleBar" >
</activity>
<activity
    android:name="com.example.WelcomeAlmostDone"
    android:label="@string/app_name"
    android:screenOrientation="portrait"
    android:theme="@android:style/Theme.Black.NoTitleBar" >
</activity>
<activity
    android:name="com.example.PasswordRegistration"
    android:label="@string/app_name"
    android:screenOrientation="portrait"
    android:theme="@android:style/Theme.Black.NoTitleBar" >
</activity>
Detwiler answered 4/2, 2015 at 7:23 Comment(0)
C
5

If you are using Xamarin C#, some of these solutions will not work. Here is the solution I found to work.

[Activity(MainLauncher = true, Icon = "@drawable/icon", ScreenOrientation = ScreenOrientation.Portrait)]

Above the class works well, similar to the other solutions. Also, it is not globally applicable and needs to be placed in each activity header.

Cavie answered 20/3, 2016 at 14:52 Comment(1)
What do you mean by "Above the class works well"?Uni
E
4

Add a class inside the oncreate() method:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Enroot answered 2/1, 2016 at 4:54 Comment(1)
How does that add a class?Uni
T
4

You can force your particular activity to always remain in portrait mode by writing this in your manifest.xml file:

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

You can also force your activity to remain in portrait mode by writing following line in your activity's onCreate() method:

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_layout);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
Toilette answered 16/1, 2017 at 6:25 Comment(0)
R
4

Either in the manifest class:

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

Or programmatically:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

Note: you should call this before setContentView method for your activity in onCreate().

Redmer answered 13/5, 2018 at 17:23 Comment(1)
@PeterMortensen press ctrl+N, then type manifestRedmer
E
4

Add the below command to your project,

npm install

npm i react-native-orientation-locker

Then you use a manifest class like, React_Native (Your Project Folder)/ android/app/src/main/AndroidManifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.payroll_react">

  <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>

  <application
    android:name=".MainApplication"
    android:label="@string/app_name"
    android:icon="@mipmap/ic_launcher"
    android:allowBackup="false"
    android:theme="@style/AppTheme">
    <activity
      android:name=".MainActivity"
      android:label="@string/app_name"
      android:screenOrientation="landscape"
      android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
      android:windowSoftInputMode="adjustResize">
      <intent-filter>
          <action android:name="android.intent.action.MAIN" />
          <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>
    <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
  </application>

</manifest>
Evaporite answered 27/12, 2018 at 9:14 Comment(0)
G
3
<android . . . >
    . . .
    <manifest . . . >
        . . .
        <application>
            <activity
                android:name=".MyActivity"
                android:screenOrientation="portrait"
                android:configChanges="keyboardHidden|orientation">
            </activity>
        </application>
    </manifest>
</android>
Groundnut answered 4/9, 2012 at 6:30 Comment(0)
A
3
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.co.nurture.bajajfinserv">
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>

    <application

        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity" android:screenOrientation="portrait">

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

We can restrict the Activity in portrait or landscape mode by using the attribute or android:screenOrientation.

If we have more than one activity in our program then we have the freedom to restrict any one of activity in any one the mode and it never affects the others which you don't want.

Abstracted answered 26/7, 2017 at 12:3 Comment(0)
C
2

In the <apphome>/platform/android directory, create AndroidManifest.xml (copying it from the generated one).

Then add android:screenOrientation="portrait" to all of the activity elements.

Catarinacatarrh answered 19/9, 2011 at 10:46 Comment(0)
G
2

Add android:screenOrientation="portrait" in the AndroidManifest.xml file.

For example:

<activity 
    android:name=".MapScreen"
    android:screenOrientation="portrait"></activity>
Gavelkind answered 1/2, 2012 at 7:42 Comment(0)
D
2

It worked for me. Try to add this code in the AndroidManifest file:

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:screenOrientation="portrait"
    android:theme="@style/AppTheme">
    ....
    ....
</application>
Dishonest answered 6/2, 2018 at 9:53 Comment(3)
I would have been a great solution, as you don't have to set per activity. Unfortunately, doesn't work in my app.Pithecanthropus
Is "AndroidManifest" the (literal) name of the file?Uni
Didn't work for API 33Interleaf
M
1

The following attribute on the activity in AndroidManifest.xml is all you need:

android:configChanges="orientation"

So, full activity node:

<activity
    android:name="Activity1"
    android:icon="@drawable/icon"
    android:label="App Name"
    android:configChanges="orientation">
Mandle answered 17/7, 2013 at 22:53 Comment(1)
There are so much answers left, you should provide more information, why one should use yours. Especially docs say's not using this Option: "Note: Using this attribute should be avoided and used only as a last resort. Please read Handling Runtime Changes for more information about how to properly handle a restart due to a configuration change." developer.android.com/guide/topics/manifest/…Scorecard
R
1

In Kotlin, the same can be programmatically achieved using the below:

requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
Roentgenology answered 11/6, 2017 at 15:7 Comment(0)
C
1

There are several ways to achieve this:

1. Via Manifest : Open the AndroidManifest.xml file, Locate the <activity> tag for the activity you want to disable landscape mode for. Add the android:screenOrientation attribute to the <activity> tag and set its value to one of these:

Constant Description
portrait Would like to have the screen in a portrait orientation: that is, with the display taller than it is wide, ignoring sensor data
(❤ Never rotate)
userPortrait Would like to have the screen in portrait orientation, but if the user has enabled sensor-based rotation then we can use the sensor to change which direction the screen is facing
sensorPortrait Would like to have the screen in portrait orientation, but can use the sensor to change which direction the screen is facing
nosensor Always ignore orientation determined by orientation sensor: the display will not rotate when the user moves the device. This can be useful for apps that need to be displayed in a specific orientation, such as games or video players.
(❤❤ Never rotate)
<activity
   ...
   android:screenOrientation="portrait"
   ...
   >
....
</activity>

You can read the full list of screen orientations here

2. Programmatic way : If you need a high degree of control over the UI behavior, use this approach. However, the programmatic way can be more verbose and difficult to maintain.

if (useSetting_forcePortrait==true) { // some condition
    // Set the orientation to portrait
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
   } else {
    // Re-enables the orientation changes
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
   }

IMPORTANT : Always test your app on different screen sizes, especially on large screens and desktop devices

Connote answered 21/11, 2023 at 13:47 Comment(0)
V
0

If your activity is related to the first device orientation state, get the current device orientation in the onCreate method and then fix it forever:

int deviceRotation = ((WindowManager) getBaseContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getOrientation();

if(deviceRotation == Surface.ROTATION_0) {
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
else if(deviceRotation == Surface.ROTATION_180)
{
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
}
else if(deviceRotation == Surface.ROTATION_90)
{
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
else if(deviceRotation == Surface.ROTATION_270)
{
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
}
Ventre answered 22/9, 2016 at 15:14 Comment(0)
I
-1

Add android:screenOrientation="portrait" in your manifest. If you want to apply a mode for a specific activity, define this in your desired activity tag. Or define in the application tag for the whole app. Like:

<application
    <!-- ... -->
    android:screenOrientation="portrait"
</application>
Influenza answered 2/7, 2020 at 6:46 Comment(3)
android:screenOrientation="portrait" applies to activity tag.Ferrer
@jstuardo: What is your point? Is something incorrect? Should something be changed?Uni
This won't work since android:screenOrientation="portrait" only applies to the activity tag as @Ferrer clarified above.Interleaf

© 2022 - 2024 — McMap. All rights reserved.