Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

android - Why can't I access a component from my xml file by declaring an object globally?

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?

question from:https://stackoverflow.com/questions/65943619/why-cant-i-access-a-component-from-my-xml-file-by-declaring-an-object-globally

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...