androidkotlinandroid-recyclerviewkotlin-lateinit

RecyclerView lateinit property mClickListener has not been initialized


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

Solution

  • 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