325

I'm trying to force the "portrait" mode for my application because my application is absolutely not designed for the "landscape" mode.

After reading some forums, I added these lines in my manifest file:

<application 
  android:debuggable="true"
  android:icon="@drawable/icon" 
  android:label="@string/app_name"
  android:screenOrientation="portrait">

But it doesn't work on my device (HTC Desire). It switches from "portrait" lo "landscape", ignoring the lines from the manifest file.

After more forums reading, I tried to add this in my manifest file:

<application 
  android:debuggable="true"
  android:icon="@drawable/icon" 
  android:label="@string/app_name"
  android:configChanges="orientation"       
  android:screenOrientation="portrait">

and this function in my activity class:

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

But again, no luck.

12 Answers 12

571

Don't apply the orientation to the application element, instead you should apply the attribute to the activity element, and you must also set configChanges as noted below.

Example:

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

This is applied in the manifest file AndroidManifest.xml.

10
  • 36
    What's the configChanges for?
    – Dror
    Oct 23, 2012 at 20:05
  • 80
    @Orchestrator, configChanges means that the configuration change is handled by the activity itself. Without it, the activity will be restarted if there is an orientation change. You might ask, if you've specified that the orientation is "portrait" how would it ever change? It can change if you launch another activity that alters the orientation, then that new activity exits, returning you back to your activity. For example, the default image capture intent on the Samsung Galaxy S3 does that in certain orientations. Jan 8, 2013 at 0:12
  • 2
    @GordonMcCreight , Can you please explain this with a real example " You might ask, if you've specified that the orientation is "portrait" how would it ever change? It can change if you launch another activity that alters the orientation, then that new activity exits, returning you back to your activity." Sep 1, 2013 at 16:12
  • 4
    Sure thing, @TusharPandey. If I recall correctly, the one place this caused us grief was was when our activity launched the default image capture intent on the Samsung Galaxy S3. Basically, we just wanted to take a picture and get the results. However, when the camera intent returned, it caused an orientation change that wiped out the state in our activity, since we didn't believe we needed to protect against that (given that our entire app was only ever in "portrait" orientation). How and why the Galaxy S3 does this is beyond my (admittedly limited) understanding. Sep 2, 2013 at 23:08
  • 12
    Why is "keyboardHidden" included? May 30, 2014 at 1:07
26

Note that

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

is added in the manifest file - where the activity is defined.

15

If you are having a lot activity like mine, in your application Or if you dont want to enter the code for each activity tag in manifest you can do this .

in your Application Base class you will get a lifecycle callback

so basically what happens in for each activity when creating the on create in Application Class get triggered here is the code ..

public class MyApplication extends Application{

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

  registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle bundle) {
                activity.setRequestedOrientation(
                        ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);


// for each activity this function is called and so it is set to portrait mode


            }

            @Override
            public void onActivityStarted(Activity activity) {

            }

            @Override
            public void onActivityResumed(Activity activity) {

            }

            @Override
            public void onActivityPaused(Activity activity) {

            }

            @Override
            public void onActivityStopped(Activity activity) {

            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {

            }

            @Override
            public void onActivityDestroyed(Activity activity) {

            }
        });
}

i hope this helps.

1
  • 1
    Efficient answer! this should be the correct answer, especially for those who are developing complex apps that heavily depend on large numbers of Activity. Jun 5, 2020 at 15:55
14

I think android:screenOrientation="portrait" can be used for individual activities. So use that attribute in <activity> tag like :

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

Set force Portrait or Landscape mode, Add lines respectively.

Import below line:

import android.content.pm.ActivityInfo;

Add Below line just above setContentView(R.layout.activity_main);

For Portrait:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//Set Portrait

For Landscap:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//Set Landscape

This will definitely work.

3
  • 1
    This fails with Android 9 on some devices - screen rotation transition is visible to a brief moment even if you only use PORTRAIT
    – Igor
    Mar 29, 2019 at 11:41
  • Can you please specify the device info in which you have face this, if possible Mar 29, 2019 at 12:14
  • @ParthPatel HUAWEI YAL-L21, Android: 10 (SDK: 29)
    – Alex Smith
    Sep 29, 2020 at 13:40
4

According to Android's documentation, you should also often include screenSize as a possible configuration change.

android:configChanges="orientation|screenSize"

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.

Also, if you all include value keyboardHidden in your examples, shouldn't you then also consider locale, mcc, fontScale, keyboard and others?..

0
3

I had this line in my AndroidManifest.xml

<activity 
    android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale"
    android:label="@string/app_name" android:name="Project Name"
    android:theme="@android:style/Theme.Black.NoTitleBar">

Which I changed to (just added android:screenOrientation="portrait")

<activity 
    android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale"
    android:label="@string/app_name" android:name="Project Name"
    android:screenOrientation="portrait"
    android:theme="@android:style/Theme.Black.NoTitleBar">

This fixed things for me.

2

Something to complement: I have updated an app recently, the previous was working in both landscape and portrait mode, and I want the updated version should work in portrait mode, so I added

android:screenOrientation="portrait"

to the corresponding activity, and it just crashed when I tested the update. Then I added

android:configChanges="orientation|keyboardHidden"

too, and it works.

2
  • 1
    If this is not an answer for the question, may be adding it as comment would help.
    – JPReddy
    Jun 24, 2014 at 12:21
  • Check that you added it to the activity not for application block Apr 27, 2018 at 11:50
2

If you wish to support different orientations in debug and release builds, write so (see https://developer.android.com/studio/build/gradle-tips#share-properties-with-the-manifest).

In build.gradle of your app folder write:

android {
    ...
    buildTypes {
        debug {
            applicationIdSuffix '.debug'
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            // Creates a placeholder property to use in the manifest.
            manifestPlaceholders = [orientation: "fullSensor"]
        }
        release {
            debuggable true
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            // Creates a placeholder property to use in the manifest.
            manifestPlaceholders = [orientation: "portrait"]
        }
    }
}

Then in AndroidManifest you can use this variable "orientation" in any Activity:

<activity
    android:name=".LoginActivity"
    android:screenOrientation="${orientation}" />

You can add android:configChanges:

manifestPlaceholders = [configChanges: "", orientation: "fullSensor"] in debug and manifestPlaceholders = [configChanges: "keyboardHidden|orientation|screenSize", orientation: "portrait"] in release,

<activity
    android:name=".LoginActivity"
    android:configChanges="${configChanges}"
    android:screenOrientation="${orientation}" />
1

I think you want to add android:configChanges="orientation|keyboardHidden" to your activity? Otherwise the activity is restarted on config-change. The onConfigurationChanged would not be called then, only the onCreate

0

To make your whole app run on complete Portrait mode or complete Landscape mode you have to do a very simple thing.

  1. Go to your app's manifest folder
  2. See the activity in which intent-filter is defined. It's basically the first activity which opens when your app is launched.
  3. Inside this activity add android:screenOrientation="portrait"

This will make your whole app run on Portrait mode or you can also set it to run on Landscape mode.

-17

Short answer: Don't do it.

Redesign your app so that it can run in both portrait and landscape mode. There is no such thing as a UI that can't be designed to work in both portrait and landscape; only lazy or unimaginative developers.

The reason why is rather simple. You want your app to be usable by as wide an audience as possible on as many different devices as possible. By forcing a particular screen orientation, you prevent your app from running (usably) on devices that don't support that orientation and you frustrate and alienate potential customers who prefer a different orientation.

Example: You design your app to force portrait mode. A customer downloads the app on a 2-in-1 device which they use predominantly in landscape mode.
Consequence 1: Your app is unusable, or your customer is forced to undock their device, rotate it, and use it in an orientation that is not familiar or comfortable for them.
Consequence 2: The customer gets frustrated by your app's non-intuitive design and finds an alternative or ditches the app entirely.

I'm fighting with this with an app right now and as a consumer and a developer, I hate it. As useful as the app is, as fantastic as the features are that it offers, I absolutely hate the app because it forces me to use an orientation that is counter to every other way that I use my device.

You don't want your customers to hate your app.


I know this doesn't directly answer the question, so I want to explain it in a little more detail for those who are curious.

There is a tendency for developers to be really good at writing code and really terrible at design. This question, though it sounds like a code question and the asker certainly feels like it's a code question, is really a design question.

The question really is "Should I lock the screen orientation in my app?" The asker chose to design the UI to function and look good only in portrait mode. I suspect it was to save development time or because the app's workflow is particularly conducive to a portrait layout (common for mobile games). But those reasons neglect all the real important factors that motivate proper design.

  1. Customer engagement - you want your customers to feel pulled into your app, not pushed out of it. The app should transition smoothly from whatever your customer was doing prior to opening your app. (This is the reason most platforms have consistent design principles, so most apps look more or less alike though they don't have to.)

  2. Customer response - you want your customers to react positively to your app. They should enjoy using it. Even if it's a payroll app for work, it should be a pleasure for them to open it and clock in. The app should save your customers time and reduce frustration over alternatives. (Apps that annoy users build resentment against your app which grows into resentment against your brand.)

  3. Customer conversion - you want your customers to be able to quickly and easily move from browsing to interacting. This is the ultimate goal of any app, to convert impressions into revenue. (Apps that don't generate revenue are a waste of your time to build, from a business perspective.)

A poorly designed UI reduces customer engagement and response which ultimately results in lower revenue. In a mobile-centric world (and particularly on the subject of portrait/landscape display modes), this explains why responsive web design is such a big deal. Walmart Canada introduced responsive design on their website in November 2013 and saw a 20% increase in customer conversion. O'Neill Clothing implemented responsive web design and revenue from customers using iOS devices increased 101.25%, and 591.42% from customers using Android devices.

There is also a tendency for developers to focus intently on implementing a particular solution (such as locking display orientation), and most of the developers on this site will be all too glad to help implement that solution, without questioning whether that is even the best solution to the problem.

Locking your screen orientation is the UI design equivalent of implementing a do-while loop. Are you really sure you want to do it that way, or is there a better alternative?

Don't force your app into a single display mode. Invest the extra time and effort to make it responsive.

12
  • 4
    I understand and agree with you about that being a poorly designed UI. But that doesn't change the fact that you MAY NEED to do so, and nonetheless the framework should have those capabilities, in general. You never know what future apps will be like and need to do, so the question is still valid. Aug 22, 2017 at 23:29
  • 1
    You're not wrong. I think my answer was partly fueled by frustration I have with a few apps that do this unnecessarily and it completely ruins the experience. I will say that the number of legitimate cases for locking the display mode is infinitesimally small (and still doable and preferable, just not within budget). This brings to mind other problems; with coding becoming as easy as it has there are a lot of amateur developers writing apps because they know code but without learning how to do UI or design, or even basic best practices (Java apps that install in \AppData - EWWWW).
    – Thomas
    Aug 23, 2017 at 16:22
  • 1
    I'm building a VR app. The orientation MUST BE landscape for the glasses to do their magic. That's one example of a UI that can't be designed to work in both portrait and landscape. Games also may have to force a certain orientation. I bet there are tons of legitimate cases.
    – Raslanove
    May 12, 2018 at 23:32
  • 1
    While StackExchange exists to answer specific questions, answers should be written to apply as generally as possible so that those answers are useful to others. Development is a lot more than just writing code and the reason there are so many junk applications in the world is because so many developers forget - or never learn - this important principle. I would personally add that if you're doing VR on a phone you're doing VR wrong - but cost has pushed demand for VR onto platforms that shouldn't ever support it.
    – Thomas
    Sep 12, 2018 at 21:18
  • 4
    I don't disagree with this answer, but it's answering a question that wasn't asked.
    – bmovement
    Dec 19, 2019 at 15:52

Not the answer you're looking for? Browse other questions tagged or ask your own question.