How can I disable landscape mode in Android? - android

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

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.

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

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().

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.

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);

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>

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.

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);
}
....
});
}
}

Use this in onCreate() of the Activity
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

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

Just add this attribute in your activity tag.
android:screenOrientation="portrait"

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......
}

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

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);
}
}

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

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>

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.

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

Add a class inside the oncreate() method:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

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);
}

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().

<android . . . >
. . .
<manifest . . . >
. . .
<application>
<activity
android:name=".MyActivity"
android:screenOrientation="portrait"
android:configChanges="keyboardHidden|orientation">
</activity>
</application>
</manifest>
</android>

<?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.

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>

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.

Add android:screenOrientation="portrait" in the AndroidManifest.xml file.
For example:
<activity
android:name=".MapScreen"
android:screenOrientation="portrait"></activity>

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>

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">

In Kotlin, the same can be programmatically achieved using the below:
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT

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);
}

Related

why is onCreate() being called after onConfigurationChanged?

I have created an activity and two layouts for the activity, one each for landscape and portrait mode. Both the layouts have same Views and IDs. In the manifest file, I have added
android:configChanges="orientation" in the activity.
Now, according to the documentation, the activity is not restarted if I mention configChanges and include the onConfigurationChanged method.
onCreate(Bundle savedInstanceState) {
Log.i("Message","inside oncreate()") ;
}
onConfigurationChanged(Configuration newConfig) {
Log.i("Message","inside onconfigurationchanged()") ;
}
My log is showing both messages when i change the orientation. Is there any way to stop the onCreate() method from being called when the orientation changes?
maybe you could add more configurations changes that you wish to ignore, since starting of a certain API on android, the orientation consist of other flags , as the documentation says about "orientation" :
The screen orientation has changed — the user has rotated the device.
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, please try to use , and tell us if it helped :
android:configChanges=orientation|screenSize"
here's the documentation about "screenSize":
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). Added in API level 13.
EDIT: here's my simple code to show that it works:
public class MainActivity extends Activity {
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i("Message","inside oncreate()");
}
#Override
public void onConfigurationChanged(final Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Log.i("Message","inside onconfigurationchanged()");
}
}
manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.test" android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" />
<application android:allowBackup="true" android:icon="#drawable/ic_launcher"
android:label="#string/app_name" android:theme="#style/AppTheme">
<activity android:name="com.example.test.MainActivity"
android:label="#string/app_name" android:configChanges="orientation|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Official documentation said that "orientation" in manifest is able to prevent restarts when the screen orientation changes and "keyboardHidden" to prevent restarts when the keyboard availability changes.
All you need to do is declare the following codes in your manifest:
<activity android:name=".MyActivity"
android:configChanges="orientation|keyboardHidden"
android:label="#string/app_name">
It works for my project.
If it doesn't work, try to change "keyboardHidden" to "screenSize".

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>

How to control landscape and portrait programmatically in android?

I developed on application using android sdk 4.0 and I install that .apk file in my samsung tab. When I run that application it is working properly. If I change the tab portrait to landscape or in reverse the screen also changed.
But my requirement is irrespective of changing the mode either portrait to landscape to Landscape to portrait, my application should run in portrait mode only.
add android:screenOrientation="portrait" for each activity in your manifest.xml file.
You can do this programmatically too, for all your activities making an AbstractActivity that all your activities extends.:-
public abstract class AbstractActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
You can define mode in AndroidManifest.xml as follows,
android:screenOrientation="portrait" after the android:name=".activityName"
for example like this,
<activity android:name=".MainActivity" android:label="#string/app_name" android:screenOrientation="portrait">
and from activity class you can use following code,
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
You can use this for landscape
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
To change to portrait mode, use the
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
In your manifest file,
<activity android:name=".MainActivity" android:label="#string/app_name" android:screenOrientation="portrait">
Then add this to your java class:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
If you search first, you'll find this question answered already. I'll post the answer again here though.
Go to your manifest file, and under the activity that you want to keep portrait only, insert the following line
android:screenOrientation="portrait"
An example is given below.
<activity android:name=".YourActivity"
android:label="Your Activoity"
android:screenOrientation="portrait">
this will make your activity forced to be in portrait mode only, even if you hold the device in landscape mode.

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

Force an Android activity to always use landscape mode

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.

Categories

Resources