Home > front end >  How to use "override fun onClick” inside onBindViewHolder in Kotlin?
How to use "override fun onClick” inside onBindViewHolder in Kotlin?

Time:04-13

I want the recycler view to listen to buttons click that exist in other fragments. Where I added the person to the database in the first fragment and the added person should be appeared in the recycler view of the second fragment after I click add. The same code can work in java but can't in Kotlin. The problem with the override of onClick ("Modifier 'override' is not applicable to 'local function'"). Is there a solution to this issue?

The Code is:

override fun onBindViewHolder(holder: ViewHolder, position:Int) {
    holder.mRow = mData[position]
    holder.Personname.text = mData[position].name
    holder.Personage.text = mData[position].age.toString()

    holder.mView.setOnClickListener (
        View.OnClickListener {
            override fun onClick{
                if (null != mListener) {
                    mListener.onFragmentListenr(holder.mRow)
                }
            }
        }
    )
  }

CodePudding user response:

Do like this...

holder.mView.setOnClickListener(object : View.OnClickListener {
            override fun onClick(v: View?) {
                mListener?.onFragmentListenr(holder.mRow)
            }
})

CodePudding user response:

It can be simplified to this

holder.mView.setOnClickListener {
    mListener?.onFragmentListenr(holder.mRow)
}
  • Related