I’m working on an Android app that has both Kotlin and Java activities. I want to handle screen orientation correctly depending on the device and the activity type. There are three main cases:
- Phone screens → always portrait.
- Tablet screens with most activities → can rotate freely.
- Tablet screens with restricted activities → cannot rotate; the activity stays in the orientation it was opened in (portrait or landscape).
As you can see in the code below, for "locked" activities I need to get the current orientation and then explicitly force the same orientation. Using requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LOCKED doesn’t seem to work as expected.
I’m a bit confused about what exactly should go into AndroidManifest.xml. I’ve tried using "android:screenOrientation="locked" and android:screenOrientation="unspecified", but neither seems to work reliably. Also, I’m not sure about the best moment to set the orientation — I’ve tried both before and right after super.onCreate(), but I still face issues. For example, when switching between activities, the new activity sometimes starts in portrait and then rotates to landscape (or just stays in portrait), even though the device was already in landscape and I called the "lock logic".
Is it possible that Kotlin and Java activities are handled differently in this regard? Or could the problem be related to navigating from a Kotlin activity to a Java activity (or vice versa)?
Here’s my Kotlin code for setting the orientation:
Kotlin code:
private fun setupOrientation(){
if (!isTablet()) {
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
} else if (restrictedActivity){
val currentOrientation = resources.configuration.orientation
requestedOrientation = if (currentOrientation == Configuration.ORIENTATION_LANDSCAPE) {
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
} else {
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
}
}
}
targetSdkreaches36or higher, depending on your definition of "phone" and "tablet". "Is it possible that Kotlin and Java activities are handled differently in this regard?" -- no. "Or could the problem be related to navigating from a Kotlin activity to a Java activity (or vice versa)?" -- not just based on language. If the Java activities are legacy code, you might have other legacy bits that are impacting matters.