Detect device orientation when Activity orientation is locked

后端 未结 3 1695
悲&欢浪女
悲&欢浪女 2020-12-06 22:27

In my project, I have to lock the orientation of an activity. (I cannot recreate the activity)

I want to display a message when the user change the orientation of th

3条回答
  •  Happy的楠姐
    2020-12-06 22:48

    You can simply use OrientationEventListener to take orientation from sensor (written in Kotlin):

    class MainActivity : AppCompatActivity() {
    
        private var orientationEventListener: OrientationEventListener? = null
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            ...
    
            orientationEventListener = object : OrientationEventListener(context) {
                override fun onOrientationChanged(orientation: Int) {
                    // orientation is in degrees
    
                    // Show "The View is locked in this position ..." message if orientation is between 45° and 315°
                    viewModel.showViewIsLocked(orientation in 45..315)
                }
            }       
        }
    
        override fun onResume() {
            super.onResume()
            orientationEventListener?.enable()      
        }
    
        override fun onPause() {
            orientationEventListener?.disable()
            super.onPause()
        }
    
    }
    

提交回复
热议问题