Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggling fullscreen & orientation like YouTube

Tags:

android

I am trying to mimic the behavior of the YouTube Android app when the "fullscreen" button is clicked in the video player:

  • If device is currently in portrait, immediately rotate to landscape (even if user is still holding the device in portrait) and remain in landscape until user rotates device to landscape and then rotates back to portrait
    • If device is currently in landscape, immediately rotate to portrait (Even if user is still holding the device in portrait) and remain in portrait until the user rotates the device to portrait and then rotates back to landscape.
    • At anytime, allow the user to manually rotate their device to the desired orientation.

It seems that if I force the rotation to landscape or portrait using:

getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

or

getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

... I immediately lose the ability to detect sensor orientation changes (i.e. once the user is in landscape, and they want to manually rotate the device back to portrait).

If I change the requested orientation to unspecified or sensor in onConfigurationChanged, the orientation briefly flips to landscape/portrait (whatever I requested from above) and then snaps back to the orientation that matches how the device is held.

Any thoughts on how to achieve my goals above?

like image 497
NPike Avatar asked Apr 03 '14 20:04

NPike


1 Answers

This modification of Alexander code is working better for me

   object : OrientationEventListener(requireContext()) {
        override fun onOrientationChanged(orientation: Int) {
            val isPortrait = orientation > 345 || orientation < 15 || orientation in 165..195
            val isLandscape = orientation in 255..285 || orientation in 75..105
            if (
                (requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT && isPortrait) ||
                (requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE && isLandscape)
            ) {
                lifecycleScope.launch {
                    // adding a delay to avoid orientation change glitch
                    delay(200)
                    activity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR
                }
            }
        }
    }
like image 160
Buntupana Avatar answered Oct 28 '22 23:10

Buntupana