So here is the code in my MainActivity.kt file
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)}
var tvInput: TextView = findViewById(R.id.tvInput)
fun onDigit(view: View){
tvInput.append((view as Button).text)
}
fun onClear(view: View){
tvInput.text = ""
}
}
When I declare the object "tvInput" globally like I have done above, it keeps crashing the app, however when I declare it separately for each function it runs smoothly, How can I fix this?
findViewById()
searches the current layout for the view and throws an exception if it isn't found. But there is no current layout yet at the time the Activity class is instantiated. There is only a layout after you have called setContentView()
in the onCreate()
function. Your tvInput
property in your example is calling findViewById()
at the time the class is instantiated.
If you want to delay when it first calls findViewById()
, you can use a Lazy delegate like this, and it will resolve the issue:
val tvInput: TextView by lazy { findViewById(R.id.tvInput) }
Now it won't call findViewById()
until the first time you actually use the property, which will happen after you call setContentView()
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments