为什么不调用 onConfigurationChanged?

Jav*_*ana 3 android orientation onconfigurationchanged kotlin

我正在编写一个代码,在更改方向时更改 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!!")
    }
}
Run Code Online (Sandbox Code Playgroud)

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

我也在清单文件中将此属性添加到我的活动中

android:configChanges="orientation"
Run Code Online (Sandbox Code Playgroud)

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

Nit*_*lal 6

使用此代码获取配置

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();
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

有几件事可以尝试:

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

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