package com.example.savingstate
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
private var count = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val countTextView: TextView = findViewById(R.id.countTextView)
val increaseButton: Button = findViewById(R.id.increaseButton)
if (savedInstanceState != null) {
count = savedInstanceState.getInt("COUNT_KEY", 0)
}
countTextView.text = "Count: $count"
increaseButton.setOnClickListener {
count++
countTextView.text = "Count: $count"
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putInt("COUNT_KEY", count)
}
}
We save the current count value in onSaveInstanceState by putting it into the Bundle with a key "COUNT_KEY". When the activity is recreated, onCreate receives the savedInstanceState bundle, from which we retrieve the saved count value. This way, the counter value is preserved across configuration changes like screen rotation.
This is a simple and common way to save small pieces of UI state in Android apps.