RecyclerView lateinit属性mClickListener尚未初始化

时间:2019-06-17 06:25:06

标签: android kotlin android-recyclerview kotlin-lateinit

我已经找到了有关如何将onClickListener实施为RecyclerView的教程,但是后来我不知道为什么代码不起作用。日志中指出lateinit属性尚未初始化。我不知道为什么这么说。我将如何解决这个问题? 这是我的适配器代码:

class ListAdapter(private val data : ArrayList<test>): RecyclerView.Adapter<ListAdapter.ViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(
            LayoutInflater.from(parent.context)
                .inflate(R.layout.test, parent, false)
        )
    }
    lateinit var mClickListener: ClickListener
    fun setOnItemClickListener(aClickListener: ClickListener) {
        mClickListener = aClickListener
    }
    interface ClickListener {
        fun onClick(pos: Int, aView: View)
    }
    override fun getItemCount() = data.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val list = data[position]
        holder.view.txt.text = list.txt
        holder.view.txt2.text = list.txt2
        holder.view.txt3.text = list.txt3
        holder.view.txt4.text = list.txt4
        holder.view.txt5.text = list.txt5
    }
    inner class ViewHolder(val view: View) : RecyclerView.ViewHolder(view), View.OnClickListener {
        override fun onClick(v: View) {
            mClickListener.onClick(adapterPosition, v)
        }
        init {
            view.setOnClickListener(this)
        }
    }
}

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

1 个答案:

答案 0 :(得分:2)

这是因为要在其他实例上设置侦听器。您应该执行以下操作:

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

另一种可能性是创建一个本地val listAdapter,实例化它并设置侦听器,最后在RV的apply块中设置adapter = listAdapter