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

Time:02-18

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

CodePudding user response:

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.

  • Related