package com.example.lifecycledemo
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
private lateinit var lifecycleTextView: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
lifecycleTextView = findViewById(R.id.lifecycleTextView)
appendMessage("onCreate called")
}
override fun onStart() {
super.onStart()
appendMessage("onStart called")
}
override fun onResume() {
super.onResume()
appendMessage("onResume called")
}
override fun onPause() {
super.onPause()
appendMessage("onPause called")
}
override fun onStop() {
super.onStop()
appendMessage("onStop called")
}
override fun onDestroy() {
super.onDestroy()
appendMessage("onDestroy called")
}
private fun appendMessage(message: String) {
lifecycleTextView.append("$message\n")
}
}We override all six lifecycle methods to track when each is called. In each method, we add a line of text to the TextView to show the event. The TextView is initialized in onCreate after setting the content view. This way, as the activity moves through its lifecycle, the user sees messages updating live on the screen.
The layout file activity_main.xml should contain a ScrollView with a TextView inside to allow scrolling when messages overflow.