N
N
Newbie Ivanovich2020-04-20 15:30:06
Android
Newbie Ivanovich, 2020-04-20 15:30:06

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)
    }


need help to figure out what and how the
error occurs here itemClickListener:AdapterView

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya Pavlovsky, 2020-04-20
@NovichokIvanovich

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") 
    }       
}

or via lambda
val itemClickListener: AdapterView.OnItemClickListener = AdapterView.OnItemClickListener { p0, p1, p2, p3 ->
    TODO("not implemented") 
}

https://kotlinlang.ru/docs/reference/nested-class...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question