androidkotlin

How can I lock screen orientation to portrait for tablet? (Android)


I want to lock screen orientation to portrait for tablet. and I implemented this in onCreate() method. However, the scree orientation doesn't keep portrait and it's causing unnecessary flicker and re-creation of the activity. I don't know why. Please help me. The dialog shows when dialogUiState is not null.

if (DeviceUtils.isTablet(this) && dialogUiState != null) {
    requestedOrientation = (ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT)
   }
object DeviceUtils {
    @JvmStatic
    fun isTablet(context: Context): Boolean {
        val configuration = context.resources.configuration
        val screenLayoutSize = configuration.screenLayout and Configuration.SCREENLAYOUT_SIZE_MASK

        return screenLayoutSize > Configuration.SCREENLAYOUT_SIZE_NORMAL
    }
}

I want to know how to lock the screen orientaion to portrait for tablet.


Solution

  • You should use SCREEN_ORIENTATION_PORTRAIT to ignore sensor.

    According to the docs, SCREEN_ORIENTATION_SENSOR_PORTRAIT can still use the sensor:

    Would like to have the screen in portrait orientation, but can use the sensor to change which direction the screen is facing.