A
A
alekseyHunter2019-08-29 18:12:13
Android
alekseyHunter, 2019-08-29 18:12:13

How to remove Listener in RecyclerView?

Recently I was reading articles about memory leaks and found one in my case, namely saving the listener after deleting the fragment.
For listeners inside a fragment, everything is simple, but how to remove the Listener in the RecyclerView?
I tried to override the onViewDetachedFromWindow method, but it removes listeners from elements that have gone off the screen.

class RecAdapterObj(var items: ArrayList<Item>) : RecyclerView.Adapter<RecHolderObj>() {

    interface OnListFragmentListener {
        fun onClickListFragment(item: Item)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecHolderObj {
        val inflater = LayoutInflater.from(parent.context)
        val view = inflater.inflate(R.layout.item_obj, parent, false)

        return RecHolderObj(view)
    }

    override fun onBindViewHolder(holder: RecHolderObj, position: Int) {
        holder.bind(items[position])

        holder.itemView.setOnClickListener {
            val mListener: OnListFragmentListener
            try {
                mListener = (it?.context as OnListFragmentListener)
            } catch (e: ClassCastException) {
                throw ClassCastException(it?.context!!.toString() + " must implement onClickListFragment")
            }
            mListener.onClickListFragment(items[position])
        }
    }

    override fun onViewDetachedFromWindow(holder: RecHolderObj) {
        super.onViewDetachedFromWindow(holder)

        holder.itemView.setOnClickListener(null)
}

    override fun getItemCount(): Int {
        return items.size
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Yudakov, 2019-08-29
@alekseyHunter

It makes sense to put a click handler on the entire RecyclerView once:
https://medium.com/@harivigneshjayapalan/android-r... Putting
handlers on each list item is overkill.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question