Carmen DiMichele
Carmen DiMichele

Reputation: 855

Maintaining state through screen rotation in Kotlin

There's really no code snippet for this. I'm building an Android app in Android Studio in Kotlin with a main activity in both default portrait and lanscape modes. I'm using Android Studio auto-generated layout\activity_main.xml and layout-land\activity_main.xml layouts.

PROBLEM: When I rotate screens in the app, all widgets reset state. For example, I have a TextView, tvTitle, with a default hardcoded string, "Hello World". tvTitle normally changed to "News" while using the app in portrait mode. I then switched to landscape mode and tvTitle reverted to it's hardcoded default string, Hello. How can I retain the state of the app through rotations?

Upvotes: 1

Views: 1883

Answers (2)

Carmen DiMichele
Carmen DiMichele

Reputation: 855

Got it. The simple answer that works for me here is:

class MainActivity : AppCompatActivity() {

    private var SavedVar = "Hello"

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putString("SavedVar_KEY" ,SavedVar)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        if(savedInstanceState != null) {
            SavedVar = savedInstanceState.getString("SavedVar_KEY")
        }
        ...
    ...
}

Upvotes: 1

Horațiu Udrea
Horațiu Udrea

Reputation: 1877

You might find the solution to your particular problem after understanding the Android mechanisms for saving the application state.

I suggest that you check out the official guide.

Upvotes: 1

Related Questions