Force an Android activity to always use landscape mode - android

I am using the Android VNC viewer on my HTC G1. But for some reason, that application is always in landscape mode despite my G1 is in portrait mode. Since the Android VNC viewer is open source, I would like know how is it possible hard code an activity to be 'landscape'. I would like to change it to respect the phone orientation.

Looking at the AndroidManifest.xml (link), on line 9:
<activity android:screenOrientation="landscape" android:configChanges="orientation|keyboardHidden" android:name="VncCanvasActivity">
This line specifies the screenOrientation as landscape, but author goes further in overriding any screen orientation changes with configChanges="orientation|keyboardHidden". This points to a overridden function in VncCanvasActivity.java.
If you look at VncCanvasActivity, on line 109 is the overrided function:
#Override
public void onConfigurationChanged(Configuration newConfig) {
// ignore orientation/keyboard change
super.onConfigurationChanged(newConfig);
}
The author specifically put a comment to ignore any keyboard or orientation changes.
If you want to change this, you can go back to the AndroidManifest.xml file shown above, and change the line to:
<activity android:screenOrientation="sensor" android:name="VncCanvasActivity">
This should change the program to switch from portrait to landscape when the user rotates the device.
This may work, but might mess up how the GUI looks, depending on how the layout were created. You will have to account for that. Also, depending on how the activities are coded, you may notice that when screen orientation is changed, the values that were filled into any input boxes disappear. This also may have to be handled.

You can set the same data in your java code as well.
myActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
Other values on ActivityInfo will let you set it back to sensor driven or locked portrait. Personally, I like to set it to something in the Manifest as suggested in another answer to this question and then change it later using the above call in the Android SDK if there's a need.

In my OnCreate(Bundle), I generally do the following:
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

You can specify the orientation of an activity in the manifest. See here.
<activity android:allowTaskReparenting=["true" | "false"]
...
android:screenOrientation=["unspecified" | "user" | "behind" |
"landscape" | "portrait" |
"sensor" | "nosensor"]
...
"adjustResize", "adjustPan"] >

In the manifest:
<activity android:name=".YourActivity"
android:screenOrientation="portrait"
android:configChanges="orientation|screenSize">
In your activity:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setContentView(R.layout.your_activity_layout);

The following is the code which I used to display all activity in landscape mode:
<activity android:screenOrientation="landscape"
android:configChanges="orientation|keyboardHidden"
android:name="abcActivty"/>

A quick and simple solution is for the AndroidManifest.xml file, add the following for each activity that you wish to force to landscape mode:
android:screenOrientation="landscape"

This works for Xamarin.Android. In OnCreate()
RequestedOrientation = Android.Content.PM.ScreenOrientation.Landscape;

That's it!! Long waiting for this fix.
I've an old Android issue about double-start an activity that required (programmatically) landscape mode: setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)
Now Android make Landscape mode on start.

Arslan,
why do you want to force orientation pro grammatically, though there's already a way in manifest
<activity android:name=".youractivityName" android:screenOrientation="portrait" />

Add The Following Lines in Activity
You need to enter in every Activity
for landscape
android:screenOrientation="landscape"
tools:ignore="LockedOrientationActivity"
for portrait
android:screenOrientation="portrait"
tools:ignore="LockedOrientationActivity"
Here The Example of MainActivity
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="org.thcb.app">
<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="landscape"
tools:ignore="LockedOrientationActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity2"
android:screenOrientation="portrait"
tools:ignore="LockedOrientationActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Doing it in code is is IMO wrong and even more so if you put it into the onCreate. Do it in the manifest and the "system" knows the orientation from the startup of the app. And this type of meta or top level "guidance" SHOULD be in the manifest. If you want to prove it to yourself set a break in the Activity's onCreate. If you do it in code there it will be called twice : it starts up in Portrait mode then is switched to Landscape. This does not happen if you do it in the manifest.

For Android 4.0 (Ice Cream Sandwich) and later, I needed to add these, besides the landscape value.
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
Using only keyboardHidden|orientation would still result in memory leaks and recreation of my activities when pressing the power button.

Use the ActivityInfo (android.content.pm.ActivityInfo) in your onCreate method before calling setLayout method like this
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

use Only
android:screenOrientation="portrait"
tools:ignore="LockedOrientationActivity"

Press CTRL+F11 to rotate the screen.

Related

setting screenOrientation to portrait doesn't work

I want to run my app in portrait mode, I'm aware this isn't best practice but there are reasons to do this. and while I have disabled the rotation it still is able to rotate on some views will it doesn't on others.
I have this part of code in my Android Manifest:
<activity
android:name="<name>.app.MainActivity"
android:label="#string/app_name"
android:configChanges="keyboardHidden|keyboard|locale|orientation"
android:screenOrientation="portrait">
I'm using fragments to show different containers depending on user input.
this is the only activity that has fragments.
I have tried a few solutions on this site. including setting portrait mode on by code
You can do it something like below.
After rootView in your java add this line
getActivity().setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); // programmatically
For example:
View rootView = inflater.inflate(R.layout.activityxml, container, false);
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
And also in your manifest change it:
android:configChanges="orientation|keyboardHidden"
as
android:configChanges="keyboardHidden"
<activity
android:name="com.test.activity"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:configChanges="keyboardHidden" >
try this code
<activity android:name="com.myActivity" android:screenOrientation="portrait"
android:configChanges="keyboardHidden|orientation"
>
</activity>
use below code before super.onCreate.first line of code.it force activity to portrait(of course both side of portrait)
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
the code that you entered android:configChanges="screenSize|orientation" just force activity to don't miss it's stats on rotate(onCreate call just once and if rotate onPause will call)
add Android Manifest:
tools:ignore="LockedOrientationActivity"
android:screenOrientation="portrait">

How to Lock Android App's Orientation to Portrait in Phones and Landscape in Tablets?

I am developing an Android app whose orientation I don't want changed to landscape mode when the user rotates the device. Also, I want the locked orientation to be portrait mode on phones and landscape mode on tablets. Can this be achieved, if yes how? Thanks.
You just have to define the property below inside the activity element in your AndroidManifest.xml file. It will restrict your orientation to portrait.
android:screenOrientation="portrait"
Example:
<activity
android:name="com.example.demo_spinner.MainActivity"
android:label="#string/app_name"
android:screenOrientation="portrait" >
</activity>
if you want this to apply to the whole app define the property below inside the application tag like so:
<application>
android:screenOrientation="sensorPortrait"
</application>
Additionaly, as per Eduard Luca's comment below, you can also use screenOrientation="sensorPortrait" if you want to enable rotation by 180 degrees.
You have to add the android:screenOrientation="portrait" directive in your AndroidManifest.xml. This is to be done in your <activity> tag.
In addition, the Android Developers guide states that :
[...] you should also explicitly declare that your application requires
either portrait or landscape orientation with the
element. For example, <uses-feature android:name="android.hardware.screen.portrait" />.
I can see you have accepted an answer which doesn't solve your problem entirely:
android:screenOrientation="portrait"
This will force your app to be portrait on both phones and tablets.
You can have the app forced in the device's "preferred" orientation by using
android:screenOrientation="nosensor"
This will lead to forcing your app to portrait on most phones phones and landscape on tablets.
There are many phones with keypads which were designed for landscape mode. Forcing your app to portrait can make it almost unusable on such devices. Android is recently migrating to other types of devices as well. It is best to just let the device choose the preferred orientation.
It might be.. you have to identify it is tablet or phone by programmatically...
First check device is phone or tablet
Determine if the device is a smartphone or tablet?
Tablet or Phone - Android
Then......
if(isTablet)
{
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}else
{
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
<activity android:name=".yourActivity"
android:screenOrientation="portrait" ... />
add to main activity and add
android:configChanges="keyboardHidden"
to keep your program from changing mode when keyboard is called.
Set the Screen orientation to portrait in Manifest file under the activity Tag.
Here the example
You need to enter in every Activity
Add The Following Lines in Activity
for portrait
android:screenOrientation="portrait"
tools:ignore="LockedOrientationActivity"
for landscape
android:screenOrientation="landscape"
tools:ignore="LockedOrientationActivity"
Here The Example of MainActivity
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="org.thcb.app">
<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"
tools:ignore="LockedOrientationActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity2"
android:screenOrientation="landscape"
tools:ignore="LockedOrientationActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Set the Screen orientation to portrait in Manifest file under the activity Tag.
android:screenOrientation="locked"
in <application> for all app
in <activity> for actual activity
I would like to add to Bhavesh's answer. The problem is that if users keep the phone in landscape mode and run the app it will first go to landscape mode since it's based on sensor in manifest and will then immediately switch to portrait mode in phones because of the code in onCreate. To solve this problem below approach worked for me.
1 Declare locked orientation in manifest for activity android:screenOrientation="locked"
<activity
android:name=".overview.OverviewActivity"
android:screenOrientation="locked" />
2 Check for tablet or phone in actiivty or base activity
override fun onCreate(savedInstanceState: Bundle?) {
//check if the device is a tablet or a phone and set the orientation accordingly
handleOrientationConfiguration()
super.onCreate(savedInstanceState)
}
/**
* This function has to be called before anything else in order to inform the system about
* expected orientation configuration based on if it is a phone or a tablet
*/
private fun handleOrientationConfiguration() {
requestedOrientation = if (UIUtils.isTablet(this).not()) {
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
} else {
ActivityInfo.SCREEN_ORIENTATION_SENSOR
}
}
UIUtils.kt
fun isTablet(context: Context): Boolean {
return context.resources.configuration.smallestScreenWidthDp >= 600
}
That's it, it will launch the app in the locked mode so that if you are on phone it will be always portraited and if you are on a tablet it will rotate based on the orientation of the device. This way it will eliminate the issue on phones where it switches between landscape and portrait at the start.
Read more here about the locked mode below
https://developer.android.com/guide/topics/manifest/activity-element
Just Add:
android:screenOrientation="portrait"
in "AndroidManifest.xml" :
<activity
android:screenOrientation="portrait"
android:name=".MainActivity"
android:label="#string/app_name">
</activity>

Screen orientation and values in manifest.xml

I want to use all activities in my form in landscape or portrait.
When user select orientation - this is valid for all activities.
Tried with "behind" option orientation. According to Google - orientation will depend on previous activity.
My first activity use setRequestedOrientation to set selected from user orientation.
Next activities have to follow same orientation.
Do I have to put setRequestedOrientation in their code too? Or really on 'behind' parameter in manifest? Putting setRequestedOrientation may be cause onCreate again?
UPDATE:
Tried "portrait" and setRequestedOrientation() - result is onCreate was called 2 times.
Problem is in next activity -> because of "portrait" in first activity - android started next activity with same orientation. It ignores "landscape" orientation which was set by me.
If you want to have fixed orientation for your activities then you can use-
android:screenOrientation="portrait"
android:screenOrientation="sensorPortrait"
as an attribute to that activity in that manifest. But if you want to set the orientation runtime depending upon what was the previous orientation while launching the application, you need to check for the previous orientation in onCreate() and then set it to that value programmatically there itself using setRequestedOrientation()
UPDATE:
As pointed by #s.co.tt use android:screenOrientation="sensorPortrait" for a better support on tablets.
For more details on the different values for android:screenOrientation and what each of them do, look at the docs:
https://developer.android.com/guide/topics/manifest/activity-element.html#screen
<activity
android:name=".Android_mobile_infoActivity"
android:label="#string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
To handle the changes in orientation, add the following line in AndroidManifest.xml:
android:configChanges="orientation|screenSize"
under <activity> tag as shown below:-
<application
android:allowBackup="true"
----------
---------- >
<activity android:name=".MainActivity"
android:configChanges="orientation|screenSize">
----------
</activity>
----------
</application>
Note: Whenever there is a change in the configuration such as orientation, screenLayout, screenSize, etc., the activity is restarted and its onCreate method is called. To prevent this, we must handle any changes in configuration.
Do it programmatically, for example in an Activity base class
I tryed its working mobile and tablet. use anyone portrait or landscape.
#Override
public void onCreate(Bundle savedInstanceState) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//or
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
manifest.xml inside application tag
<activity
android:name=".Login_Activity"
android:label="#string/app_name"
android:screenOrientation="portrait" />
or
<activity
android:name=".Login_Activity"
android:label="#string/app_name"
android:screenOrientation="landscape" />
In Android studio 3.6.0
android:screenOrientation="portrait"
will give you error you have to either specify
android:screenOrientation="fullSensor" or android:screenOrientation="unspecified"
fullSensor Means either you have ON the "Rotate off" or not it will change the orientation based on you move the phone
unspecified Means if you have ON the Rotate off then it will stay only in that orientation and if not then it will change the orientation based on you move the phone.
From my experience I would recommend to setRequestedOrientation in every activity in onCreate method, onCreate won't be called again it's safe.
For now I put check in onCreate:
m_bSkip = (this.getRequestedOrientation() != MyApp.sInstance.GetScreenOrientation());
if (m_bSkip)
return;
When I enter oncreate and screen orientation is not desired - exit.
When I enter in onCreate and screen orientation is desired one - continue with initialization.
This fixes situation without need of keeping async task related to activity and check for new activity.
Of course all functions: onStart,onResume,onPausde,onStop... have to check this flag to avoid null pointer exception.
go to Android Manifest editor , down there you will see MainActivity.java
click on it , to the right - you will see a new window: scroll down and choose select orientation - "portrait"

Android, how to not destroy the activity when I rotate the device?

I have an app that works only in portrait mode, and I have made the changes in my manifest file for every activity the orientation to be portrait. But when I rotate the device, the activity recreates again.
How to not destroy the activity?
For API 12 and below: add
android:configChanges="orientation"
Add "screenSize" if you are targeting API 13 or above because whenever your orientation changes so does your screen size, otherwise new devices will continue to destroy your activity. See Egg's answer below for more information on using "screenSize"
android:configChanges="orientation|screenSize"
to your Activity in AndroidManifest.xml. This way your Activity wont be restarted automatically. See the documentation for more infos
From the official document flurin said,
Note: 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.
So if your app targets API level 13 or higher, you should set this config instead:
android:configChanges="orientation|screenSize"
The right solution is
android:configChanges="orientation|screenSize"
Android documentation:
The current available screen size has changed. This represents a change in the currently available size, relative to the current aspect ratio, so will change when the user switches between landscape and portrait. 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).*
I was messing this up for a little bit and then relized that inside the Manifest file I was putting the configChanges on the Application level and not on the Activity Level. Here is what the code looks like when it is correctly working for me.
<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:configChanges="orientation|screenSize|keyboardHidden">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
Now that Android supports split screen ("multi-window" in Android parlance), you'll probably want to add screenSize|smallestScreenSize|screenLayout|orientation as well. So to handle rotation and split screen you'll want something like this in android:configChanges
<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:configChanges="orientation|screenSize|keyboardHidden|smallestScreenSize|screenLayout">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
Look at this code in Floating Image. It has the most interesting way of handling screen rotation ever. http://code.google.com/p/floatingimage/source/browse/#svn/trunk/floatingimage/src/dk/nindroid/rss/orientation
write in manifest:
android:configChanges="orientation|screenSize|keyboardHidden"
and override this in activity that solved your problem:
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}

How is application orientation (landscape or portrait) locked?

I have tried to freeze orientation using:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Although the display stays in portrait orientation, the activity is still recreated. Any ideas how to solve this?
How can the orientation of the application be locked such that the activity is not recreated on orientation change?
First, don't use setRequestedOrientation() if you can avoid it. Use the android:screenOrientation attribute in your <activity> manifest element instead.
Second, you will also need android:configChanges="keyboardHidden|orientation" in your <activity> manifest element to prevent the destroy/recreate cycle.
A more specific example of the activity section of the AndroidManifest.xml for portrait orientation:
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:configChanges="keyboardHidden|orientation|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Where android:screenOrientation sets the initial orientation and android:configChanges voids the events that triggers the corresponding lifecycle methods on screen changes.
Try this:
1.- Set the desired screen orientation in your AndroidManifest.xml
android:screenOrientation="portrait|landscape"
It should look like this:
<application
android:allowBackup="true"
android:icon="~icon path~"
android:label="~name~"
android:supportsRtl="true"
android:screenOrientation="portrait"
android:theme="#style/AppTheme">
</application>
2.- Add this to your onCreate void(or wherever you want) in your java Activity File(Example: "MainActivity.java"):
super.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
It should look like this:
protected void onCreate(Bundle savedInstanceState) {
super.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);}
Now the screen wont move even if the Screen Rotation is on in the Device.
The best solution is to use the saved instance.
If you are locking the the screen orientation then it means you are forcing the user to use the app according to constraints set by you. So always use onSaveInstanceState. Read this link: http://developer.android.com/training/basics/activity-lifecycle/recreating.html

Categories

Resources