我是一名新手Android开发者。在我的应用程序开发中,我想处理显示(屏幕)旋转。是否有可用的监听器来处理此事件?或者是否有其他方法来处理这种情况?
谢谢和问候,
Bala
我是一名新手Android开发者。在我的应用程序开发中,我想处理显示(屏幕)旋转。是否有可用的监听器来处理此事件?或者是否有其他方法来处理这种情况?
谢谢和问候,
Bala
假设你希望自己处理方向改变,可以在manifest.xml文件中的activity标签下添加 configChanges="orientation"
属性。
<activity android:name=".MyActivity"
android:configChanges="orientation"
android:label="@string/app_name">
现在,当这些配置之一发生变化时,MyActivity不会重新启动。相反,该Activity会接收到一个 onConfigurationChanged()
的调用。
更多细节请参见:处理运行时变化
在开发API 13或更高版本(由minSdkVersion和targetSdkVersion属性声明)时,请除了“orientation”之外还包括“screenSize”。
android:configChanges="orientation|screenSize"
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
}
我在视图模型中使用Dagger进行初始化:
@ExperimentalCoroutinesApi
@HiltViewModel
open class MyViewModel
@Inject
constructor(
val screenOrientationListener: ScreenOrientationListener
) : ViewModel() {}
但你可以通过以下方式进行初始化:
val screenOrientationListener = ScreenOrientationListener(this)
如何使用它:
screenOrientationListener.observe(this, {
if(it){
//Do something if screen was rotated
}
})