Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Android studio-Kotlin how to declare global variables for XML elements (Button, TextView)

I want to declare 3 private global variables, inside my MainActivity.kt .
This is what I’m trying to do, but it doesn’t work: the app crashes every time I open it on the emulator.

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding
    private var getTextBtn = Button(this)
    private var edtTxtName = EditText(this)
    private var textViewHello = TextView(this)
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)
        
        getTextBtn = binding.getRecipeBtn
        edtTxtName = binding.edtTxtName
        textViewHello = binding.textViewHello
    }
}

I’m a newbie in Kotlin/Android Studio, so probably what I’m doing it’s totally wrong, but I can’t figure out how to do it

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You should use private lateinit var for those variables as well:

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding
    private lateinit var getTextBtn: Button
    private lateinit var edtTxtName: EditText
    private lateinit var textViewHello: TextView
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)
        
        getTextBtn = binding.getRecipeBtn
        edtTxtName = binding.edtTxtName
        textViewHello = binding.textViewHello
    }
}

Though, I’d advocate against it – you can access them from your binding anyway. The less references to maintain, the better.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading