Java how to disable screen rotation android studio

Java how to disable screen rotation android studio

To disable screen rotation in Android, you can set the screenOrientation attribute to a fixed orientation in the activity's layout file. This attribute specifies the orientation of the activity and prevents the screen from rotating to a different orientation.

Here's an example of how to set the screenOrientation attribute in an activity's layout file:

<activity
  android:name=".MainActivity"
  android:screenOrientation="portrait"
  android:label="@string/app_name">
  <intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
  </intent-filter>
</activity>
Sourc‮:e‬www.lautturi.com

The above example sets the screenOrientation attribute to "portrait", which prevents the screen from rotating to landscape orientation. You can also set the attribute to "landscape" to prevent the screen from rotating to portrait orientation.

Alternatively, you can override the onConfigurationChanged() method in your activity and handle screen orientation changes manually. This method is called when the device's configuration (e.g., screen orientation, language) changes.

Here's an example of how to override the onConfigurationChanged() method and disable screen rotation:

@Override
public void onConfigurationChanged(Configuration newConfig) {
  // Prevent the screen from rotating to a different orientation
  super.onConfigurationChanged(newConfig);
  setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}

The above example sets the requested orientation to portrait, which prevents the screen from rotating to landscape orientation. You can set the requested orientation to "landscape" to prevent the screen from rotating to portrait orientation.

Note that some devices may ignore the screenOrientation attribute or the requested orientation and allow the screen to rotate freely. To completely disable screen rotation on these devices, you may need to use additional measures, such as using device-specific APIs or rooting the device.

Created Time:2017-11-03 22:21:05  Author:lautturi