【问题标题】:Why isn't onConfigurationChanged being called?为什么不调用 onConfigurationChanged?
【发布时间】:2017-05-22 07:26:44
【问题描述】:

我正在编写一个代码,当方向改变时改变 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 = "Changed to Landscape" 而不是这个 mytext?.setText("Changed to Landscape")
  • @TerrilThomas 问题是 onConfigurationChanged fun is not called
  • mytext?.setText() 在 onCreate 方法中工作。问题是 onConfigurationChanged() 没有被调用
  • 不要在 kotlin 中使用 settext 这样的错误检查链接stackoverflow.com/questions/44096838/…

标签: android orientation kotlin onconfigurationchanged


【解决方案1】:

使用此代码获取confi chage

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"
  • @TerrilThomas 你是对的。将 android:configChanges="orientation|screenSize 添加到清单中的 Activity 使其工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多