简体   繁体   中英

Is it bad practice to pass a fragment as argument to RecyclerView.Adapter? To help onClick

I was researching best ways to implement onClick for recycler views, there are good ways to do this, but is passing the fragment and referencing a function in the fragment a decent solution? First time asking a question here so excuse the poor format.

Fragment:

class MyFragment: BaseFragment() {

    private val selectedList = ArrayList<Object>()

......
        rvTempListView.adapter = MyAdapter(
            tempGroupedList,
            this
        )
.......

    fun itemSelected(object: Object) {
        if (object in selectedList){
            selectedList.remove(object)
        } else {
            selectedList.add(object)
        }
    }
}

RecyclerView.Adapter:

class MyAdapter(val uniqueObjects: MutableList<Object>,
                val myFragment: MyFragment)
    : RecyclerView.Adapter<MyAdapter.ViewHolder>() {
    val TAG = javaClass.simpleName

.......
        cardView.setOnClickListener {
            mFragment.itemSelected(uniqueObjects[position]) {
                if (toggle){
                    ivChecked.visibility = View.VISIBLE
                    toggle = !toggle
                } else {
                    ivChecked.visibility = View.INVISIBLE
                    toggle = !toggle
                }            
            }
        }
.......

}

The above solution works great, just wondering if its bad practice or not? Thanks!

No, there's no problem with doing this. Your Adapter's lifecycle is tied to your Fragment's lifecycle, so you're not risking any memory leaks or anything like that by doing this.

You might want to do this via an interface that defines only that method in order to enforce the API between the two for separation-of-concerns reasons, but this is also fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM