3

I'm writing a code that changes the TextView's text when the orientation is changed I am using the onConfigurationChanged() listener for changing the text

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!!")
    }
}

but nothing happens not even in the Log

also I have added this attribute to my Activity in manifest file

android:configChanges="orientation"

What am I missing here ? also is there any other way to achieve this?

rsanath
  • 1,154
  • 2
  • 15
  • 24
  • In kotlin you need to use : mytext?.text = "Changed to Landscape" rather than this mytext?.setText("Changed to Landscape") – Terril Thomas May 22 '17 at 07:36
  • @TerrilThomas the issue is onConfigurationChanged fun is not called – Nithinlal May 22 '17 at 07:37
  • mytext?.setText() works while being in onCreate method. The problem is that onConfigurationChanged() is not being called – rsanath May 22 '17 at 10:13
  • Don't use settext like this in kotlin its wrong check the link http://stackoverflow.com/questions/44096838/how-to-get-and-set-a-text-to-textview-in-android-using-kotlin/44096865?noredirect=1#comment75216911_44096865 – Nithinlal May 22 '17 at 11:01

1 Answers1

6

Use this code to get the 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();
            }
        }
    }

A couple of things to try:

android:configChanges="orientation|keyboardHidden|screenSize" rather than android:configChanges="orientation"

Ensure that you are not calling setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); anywhere. This will cause onConfigurationChange() to not fire.

Nithinlal
  • 4,845
  • 1
  • 29
  • 40