Reputation: 4829
I am new the Android. In my application development, I want to handle the display (screen) rotation. Is there any listener is available to handle this event? Or is there any alternate way to handle this situation?
Thanks & Regards,
Bala
Upvotes: 7
Views: 14951
Reputation: 1
Create class "ScreenOrientationListener":
class ScreenOrientationListener @Inject constructor(@ApplicationContext private val appContext: Context) :
MutableLiveData<Boolean>() {
private var screenWasRotated: Boolean = false
private var screenRotationListener: OrientationEventListener? = null
private fun registerScreenRotationListener() {
//reset
screenWasRotated = false
screenRotationListener = object :
OrientationEventListener(appContext, SensorManager.SENSOR_DELAY_NORMAL) {
override fun onOrientationChanged(p0: Int) {
if (!screenWasRotated) {
if ((appContext.resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT && p0 in 90..290) ||
(appContext.resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE && p0 in 0..70)
) {
screenWasRotated = true
screenRotationListener?.disable()
postValue(screenWasRotated)
}
}
}
}
if (screenRotationListener?.canDetectOrientation() == true) {
screenRotationListener?.enable()
} else {
screenRotationListener?.disable()
}
}
override fun onActive() {
super.onActive()
registerScreenRotationListener()
}
override fun onInactive() {
screenRotationListener?.disable()
screenRotationListener = null
super.onInactive()
}
override fun getValue() = screenWasRotated
}
I usage Dagger to initialize it in view model:
@ExperimentalCoroutinesApi
@HiltViewModel
open class MyViewModel
@Inject
constructor(
val screenOrientationListener: ScreenOrientationListener
) : ViewModel() {}
But you can just initialize it by:
val screenOrientationListener = ScreenOrientationListener(this)
How to use it:
screenOrientationListener.observe(this, {
if(it){
//Do something if screen was rotated
}
})
Upvotes: 0
Reputation: 1647
When developing for API level 13 or higher (as declared by the minSdkVersion and targetSdkVersion attributes), include "screenSize" in addition to "orientation".
android:configChanges="orientation|screenSize"
Upvotes: 3
Reputation: 14027
Let's say you want to handle the orientation change yourself, use configChanges="orientation"
in your activity in the manifest.xml
<activity android:name=".MyActivity"
android:configChanges="orientation"
android:label="@string/app_name">
Now when one of these configurations change, MyActivity is not restarted. Instead, the Activity receives a call to onConfigurationChanged().
More details here: Handling runtime changes
Upvotes: 10