Add fragment in RecyclerView.ViewHolder

Short answer: you shouldn't use fragments inside a recyclerView, that's not what they're intended for.

Long answer: here


You should know exactly that recyclerview created your holder and drew a view for him, so you need to attach a fragment in onViewAttachedToWindowmethod of your adapter. In your "attaching fragment" method you should check if fragment manager already contains those fragments to prevent of creating multiple instances.

Adapter:

 override fun onViewAttachedToWindow(holder: RecyclerView.ViewHolder) {    
    if(holder is FragmentsHolder){
        attachFragmentToContainer(holder.flContainer)            
    }
    super.onViewAttachedToWindow(holder)
}

Method realization:

 fun attachFragmentToContainer(containerId: Int) {
    val fragment = if (fragmentManager?.fragments?.firstOrNull { it is YourFragment } == null)
        YourFragment.instance()
    else
        null

    if (fragment != null) {
        fragmentManager?.beginTransaction()
            ?.add(containerId, fragment)
            ?.commitNowAllowingStateLoss()
    }
}

This tested on big amount of users - no crashes, good perfomance.


I faced the same problem and resolved it by using the addOnChildAttachStateChangeListener RecyclerView callback on my onBindViewHolder callback :

listView.addOnChildAttachStateChangeListener(new RecyclerView.OnChildAttachStateChangeListener() {
        @Override
        public void onChildViewAttachedToWindow(@NotNull View view) {
            //Create your fragment container here using the view param and add your fragment to the container
        }

        @Override
        public void onChildViewDetachedFromWindow(@NotNull View view) {
            //Destroy the fragment container here

        }
    });