1

I've found a tutorial on how to implement onClickListener to RecyclerView but then I couldn't find out why the code doesn't work. The log says that the lateinit property has not been initialized. I am not sure why it said that. How would I be able to solve this?

This is part of the code in MainActivity:

 viewManager = LinearLayoutManager(this)
        val list = ArrayList<test>()
        recyclerView = findViewById<RecyclerView>(R.id.recyclerview).apply {
            setHasFixedSize(true)
            layoutManager = viewManager
            adapter = ListAdapter(list)
        }
        ListAdapter(list).setOnItemClickListener(object : ListAdapter.ClickListener {
            override fun onClick(pos: Int, aView: View) {
                Toast.makeText(applicationContext,"It works :)",Toast.LENGTH_SHORT).show()
            }
        })
CoderUni
  • 5,474
  • 7
  • 26
  • 58
  • Try replacing `ListAdapter(list).setOnItemClickListener` with `adapter.setOnItemClickListener` – Astha Garg Jun 17 '19 at 06:32
  • @Astha It says unresolved reference. I tried that a while ago but it wouldn't work. Thanks for helping me anyways :) – CoderUni Jun 17 '19 at 06:51
  • The declaration of `adapter` was not shown in the code, anyway the problem was clearly due to different reference. – Astha Garg Jun 17 '19 at 07:14

1 Answers1

3

It is because you are setting the listener on a different instance. You should do something like this:

recyclerView = ....apply {
    ...
    adapter = ListAdapter(list).apply {
        setOnItemClickListener(...)
    }
}

The other posibility is to create a local val listAdapter, instantiate it and set the listener and finally, in the apply block of a RV, set adapter = listAdapter

Maroš Šeleng
  • 1,600
  • 13
  • 28