为什么不调用 onConfigurationChanged?

Why isn't onConfigurationChanged being called?

我正在编写代码,在方向改变时改变 TextView 的文本 我正在使用 onConfigurationChanged() 侦听器来更改文本

override fun onConfigurationChanged(newConfig: Configuration?) {
    super.onConfigurationChanged(newConfig)

    val orientation : Int = getResources().getConfiguration().orientation
    val oTag = "Orientation Change"

    if(orientation == (Configuration.ORIENTATION_LANDSCAPE)){
        mytext?.setText("Changed to Landscape")
        Log.i(oTag, "Orientation Changed to Landscape")

    }else if (orientation == (Configuration.ORIENTATION_PORTRAIT)){
        mytext?.setText("Changed to Portratit")
        Log.i(oTag, "Orientation Changed to Portratit")
    }else{
        Log.i(oTag, "Nothing is coming!!")
    }
}

但即使在日志中也没有任何反应

此外,我已将此属性添加到清单文件中的 Activity

android:configChanges="orientation"

我在这里错过了什么? 还有其他方法可以实现吗?

使用此代码获取配置

override fun onConfigurationChanged(newConfig: Configuration?) {
        super.onConfigurationChanged(newConfig)
        if (newConfig != null) {
            if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
                Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
            } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
                Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
            }
        }
    }

有几件事要尝试:

android:configChanges="orientation|keyboardHidden|screenSize" 而不是 android:configChanges="orientation"

确保您没有在任何地方调用 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);。这将导致 onConfigurationChange() 不触发。