Setting the orientation for only 1 fragment in my activity while the rest is in portrait

后端 未结 8 1095
难免孤独
难免孤独 2020-12-05 01:52

My app needs to be in portrait mode so I set it in the manifest by:

android:screenOrientation=\"portrait\"

But I just recently added anothe

8条回答
  •  情歌与酒
    2020-12-05 02:25

    So I'm dealing with this issue now. We have only portrait mode application (for now). But there is one fragment that needs to be in landscape. We are using single Activity approach so the accepted answer will not help me.

    The fastest solution I could think of is this one.

    private var swappingOrientation = false
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    
        if(savedInstanceState == null) {
            swappingOrientation = true
            activity?.apply {
                requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
            }
        }
    }
    
    override fun onDestroy() {
        super.onDestroy()
    
        if(!swappingOrientation) {
            activity?.apply {
                requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
            }
        }
        swappingOrientation = false
    }
    

    You hold the information if you are swapping orientation or not in swappingOrientation variable. At the beggining when the fragment is created it will change orientation, only when there is no saved state. And orientation is changed back again only when it is not being currently changed.

    This is a super quick solution and it can produce screen blinking when you return to previous fragment. I also did not fully test it so it can have other issues, so keep that in mind.

提交回复
热议问题