Answer the question
In order to leave comments, you need to log in
How to correctly add a listener in android to kotlin?
decided to learn kotlin and android from head first android book and on page 301 the code of adding listener is not working
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val itemClickListener:AdapterView.OnItemClickListener = AdapterView.OnItemClickListener() {
fun onItemClick(AdapterView<?> listView, itemView: View, position:Int, id: Long) {
if(position == 0) {
val intent = Intent(MainActivity.this, DrinkCategoryActivity.class)
startActivity(intent)
}
}
}
val listView:ListView = findViewById<ListView>(R.id.list_options)
listView.setOnClickListener(itemClickListener)
}
Answer the question
In order to leave comments, you need to log in
You have not declared an anonymous class.
val itemClickListener: AdapterView.OnItemClickListener = object : AdapterView.OnItemClickListener {
override fun onItemClick(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
TODO("not implemented")
}
}
val itemClickListener: AdapterView.OnItemClickListener = AdapterView.OnItemClickListener { p0, p1, p2, p3 ->
TODO("not implemented")
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question