在Android中处理屏幕旋转

7

我是一名新手Android开发者。在我的应用程序开发中,我想处理显示(屏幕)旋转。是否有可用的监听器来处理此事件?或者是否有其他方法来处理这种情况?

谢谢和问候,

Bala


1
如果你只是想处理旋转时Activity被销毁的问题,请参考这个问题的讨论。具体来说,使用Fragment似乎是处理这个问题的推荐方式,因为你可以指定在旋转时不销毁Fragment。如果你有更一般的旋转需求,@SteD的答案是正确的。但请注意,这在Android API文档中被建议避免使用。 - brianmearns
3个回答

10

假设你希望自己处理方向改变,可以在manifest.xml文件中的activity标签下添加 configChanges="orientation" 属性。

<activity android:name=".MyActivity"
          android:configChanges="orientation"
          android:label="@string/app_name">

现在,当这些配置之一发生变化时,MyActivity不会重新启动。相反,该Activity会接收到一个 onConfigurationChanged() 的调用。

更多细节请参见:处理运行时变化


3

在开发API 13或更高版本(由minSdkVersion和targetSdkVersion属性声明)时,请除了“orientation”之外还包括“screenSize”。

android:configChanges="orientation|screenSize"

解决了我所有的问题。 - Dpedrinha

0
创建类“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 
}

我在视图模型中使用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
        }
})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接