为什么onConfigurationChanged没有被调用?

3

我正在编写一段代码,当屏幕方向改变时,会改变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!!")
    }
}

但是什么也没有发生,甚至连日志中都没有任何信息。

我还在清单文件中为我的活动添加了这个属性。

android:configChanges="orientation"

这是什么地方出了问题?还有其他实现方法吗?

在 Kotlin 中,您需要使用:mytext?.text = "已更改为横向" 而不是 mytext?.setText("已更改为横向")。 - Terril Thomas
@TerrilThomas,问题在于 onConfigurationChanged 函数没有被调用。 - Nithinlal
mytext?.setText()在onCreate方法中起作用。 问题是onConfigurationChanged()没有被调用。 - rsanath
在Kotlin中不要像这样使用settext,这是错误的,请查看以下链接:https://dev59.com/-lcP5IYBdhLWcg3worVh#44096865?noredirect=1#comment75216911_44096865 - Nithinlal
1个回答

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();
            }
        }
    }

有几件事可以尝试:

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

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


这个有效:android:configChanges="orientation|keyboardHidden|screenSize" - Terril Thomas
@TerrilThomas 你是对的。在清单文件中将android:configChanges="orientation|screenSize"添加到activity中使它正常工作。 - rsanath

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