Force "portrait" orientation mode
Asked Answered
T

12

327

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.

Troyes answered 3/2, 2011 at 11:37 Comment(0)
O
575

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.

Oruro answered 3/2, 2011 at 11:41 Comment(10)
What's the configChanges for?Groom
@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.Checkmate
Is it still necessary to override onConfigurationChanged in your code?Udell
@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."Hausmann
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.Checkmate
Why is "keyboardHidden" included?Lolitaloll
@Orchestrator: According to Android guide, android:configChanges -> Lists configuration changes that the activity will handle itself. When a configuration change occurs at runtime, the activity is shut down and restarted by default, but declaring a configuration with this attribute will prevent the activity from being restarted. Instead, the activity remains running and its onConfigurationChanged() method is called.Claudetta
@gonzobrains: "keyboardHidden" - The keyboard accessibility has changed — for example, the user has revealed the hardware keyboard. "orientation" - The screen orientation has changed — the user has rotated the device. More details can be found at developer.android.com/guide/topics/manifest/…Claudetta
as per latest guidelines, one must also include screenSize and screenLayout. If you want to manually handle orientation changes in your app you must declare the "orientation", "screenSize", and "screenLayout" values in the android:configChanges attributes.Fukuoka
...and if my app only uses one Activity and some set of Fragments, and I decided to just not include the configChanges, then what? Would it punch me back somehow?Albin
A
27

Note that

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

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

Aleciaaleck answered 25/5, 2013 at 14:59 Comment(0)
G
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.

Gloze answered 14/11, 2015 at 7:33 Comment(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.Carlenacarlene
S
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>
Selves answered 3/2, 2011 at 11:42 Comment(0)
E
14

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.

Erythrism answered 31/5, 2018 at 4:14 Comment(3)
This fails with Android 9 on some devices - screen rotation transition is visible to a brief moment even if you only use PORTRAITHexaemeron
Can you please specify the device info in which you have face this, if possibleErythrism
@ParthPatel HUAWEI YAL-L21, Android: 10 (SDK: 29)Josefjosefa
F
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?..

Ferrate answered 29/7, 2014 at 10:38 Comment(0)
D
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.

Danforth answered 21/1, 2014 at 10:20 Comment(0)
G
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.

Galactic answered 24/6, 2014 at 11:58 Comment(2)
If this is not an answer for the question, may be adding it as comment would help.Horsewhip
Check that you added it to the activity not for application blockRibbon
R
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}" />
Runway answered 12/12, 2018 at 10:0 Comment(0)
A
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

Alexander answered 3/2, 2011 at 11:43 Comment(0)
S
-1

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.

Stem answered 5/11, 2021 at 19:55 Comment(0)
T
-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.

Trypsin answered 14/8, 2017 at 0:35 Comment(12)
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.Oralla
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).Trypsin
I know.. totally agree with you! CheersOralla
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.Patrology
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.Trypsin
I reread this two years later and watch it gain down votes and it occurs to me that many developers on StackOverflow probably don't know why you shouldn't use do-while loops...Trypsin
I don't disagree with this answer, but it's answering a question that wasn't asked.Copybook
Who knows what the application need is the developer himself. Some apps are designed to act on a specific kind of device for some specific reason. If an user dowload an app to a device that it isn't intended to work, he is not part of the intended audience of the appAzote
@Azote - My point is that developers often don't know the design needs of an application. Writing a UI is a technical problem. Designing a UI is an artistic problem and one which many developers today are unequipped to solve. The tl;dr is that if a developer thinks they need to lock the orientation of their app, they're wrong. And that is apparently a very hard pill to swallow for a lot of stackoverflow community members. And for the record, no developer ever knows the audience of their app, "intended" or not, and artificially limiting your audience with poor UI design is also wrong.Trypsin
@Thomas, when some user ask for a technical way to do something, is polite to consider that he know what he is doing. You can make considerations about the design or another UX aspects, but is no good deny the information to do it. On social network apps, for instance, Facebook and Twitter supports landscape mode, Instagram and Pinterest don't. Is a proper design decision to offer to the user the best experience with the specific content. As Mathias Duarte points, you can deviate from rules with purpose.Azote
Given this question, the preponderance of really terrible apps on the market, and the popularity of this website, I think it is prudent to expect that most developers do, in fact, not know what they are doing. Lots of people provided technical answers to this asker's question, so they have the solution if they want it. Understanding when (and when not) to apply that solution was my purpose in answering. "The best user experience" is one that adapts to how the user chooses to interact with that content - whether in portrait OR landscape mode. Which is what I wrote. Read my answer next time.Trypsin
I couldn't fight the urge to upvote this, even though it doesn't answer the question asked. Sometimes you just have to remember that Chromebooks exist.Alleged

© 2022 - 2024 — McMap. All rights reserved.