简体   繁体   中英

How to lock the screen to not allow rotate at one fragment

Having a pager fragment and when one fragment is scrolled in would like it to be lock at portrait mode, and others should allow rotate.

override fun onPageSelected(position: Int) {
    val item = getDataItem(position)   
    if (item is SpecialItem) {

        if (context?.resources?.configuration?.orientation == Configuration.ORIENTATION_PORTRAIT) {
            activity?.requestedOrientation = ActivityInfo.ORIENTATION_PORTRAIT

            // or tried activity?.requestedOrientation = ActivityInfo.ORIENTATION_PORTRAIT

           // or tried activity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LOCKED

        }


    } else {
        activity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR
    } 
......
}

But after the call of

activity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE

it can still rotate the screen.

What is the right way to lock the screen here?

What is the difference between

activity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR

and

activity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_NOSENSOR

and

activity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_FULL_USER

Update

Thanks for JensV point out it was a typo and it should be ORIENTATION_PORTRAIT there and it is working.

Now the question only what are the difference, and should it be using

activity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LOCKED

or

activity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT

// or activity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT

Posting as an answer as I solved your problem.

Root problem was that SCREEN_ORIENTATION_LANDSCAPE was being used instead of SCREEN_ORIENTATION_PORTRAIT

The answer to your second question: I'd go with SCREEN_ORIENTATION_UNSPECIFIED which will reset back to not having set anything specific.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM