What is the best way to declare a variable for a TextView that changes during lifecycle of Activity?

135 Views Asked by At

I decided to learn how lifecycle of an Activity works via changing different properties of a simple TextView at each stage of a cycle. I wanted to know what is the best way to declare a variable for the said TextView so I could use it within each stage. My current solution is declaring a variable with lateinit var and and assigning a value within onCreate

private lateinit var helloView: TextView

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

        helloView = findViewById(R.id.helloText)

        helloView.text = "foo"
    }

    override fun onPause() {
        super.onPause()

        helloView.setTextColor(Color.RED)
    }

    override fun onRestart() {
        super.onRestart()

        helloView.text = "bar"
    }

1

There are 1 best solutions below

0
On

An easier way is to use Logcat instead. Use it in every stage of the lifecycle with a message and check when every message is displayed. With your attempt it will be difficult to see changes if you want to use more then just these lifecycle stages e.g. onStop or onDestroy.

Also a good start is to read this guide https://developer.android.com/guide/components/activities/activity-lifecycle