I am new to android studio and wanted to make a pretty basic app. The problem is after creating an xml file and giving it id as btnApply
, i tried to print something when it gets clicked. I think the code is correct as I have been following a youtube tutorial, but something else like my settings is not allowing me to access the xml file elements. Any fixes??
package com.example.applicationone
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
btnApply.setOnClickListner{
Log.d("MainActivity", "Button Clicked")
}
}
CodePudding user response:
To use btnApply
, you first have to declare it. Instead use findViewById<Button>(R.id.btnApply)
Also, if you want to learn android, google's course might be a good start.
Use the code below if btnApply
is your button's id
findViewById<Button>(R.id.btnApply).setOnClickListner{
Log.d("MainActivity", "Button Clicked")
}
CodePudding user response:
If you've been following some tutorial, it's probably using the deprecated Kotlin synthetics library that automagically looks up views when you refer to them without declaring them. Either move to View Binding (which is basically the same thing except you access your IDs on a Binding
object you initialise) or look them up the basic way with findViewById
like in Vaishnav's answer