简体   繁体   中英

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

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

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 eg onStop or onDestroy.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM