Christian
Christian

Reputation: 26427

FragmentTranscation within a RecyclerView.ViewHolder

I have a complex RecyclerView.ViewHolder. Given that my app is targeted at tablets there's more space that allows for more complexity in the UI. When the user clicks a button inside that ViewHolder, I have to display another RecyclerView inside the ViewHolder. Given that the secondary RecyclerView is only needed when the user presses the button I don't want to load it immediately but seperate it out into a Fragment that will only be loaded when the user clicks the button within the ViewHolder

In the XML for my ViewHolder I declared a Framelayout via:

<FrameLayout
    android:id="@+id/fragmentContainer"
    app:layout_constraintTop_toBottomOf="@id/counter"

    android:layout_height="wrap_content"
    android:layout_width="match_parent"/>

I call the items that the primary RecyclerView displays stack. Unfortunately, when the user clicks on the button of the stack with the id=5 the secondary Fragment for the secondary RecyclerView gets added to the ViewHolder for id=1 that gets listed first in the primary RecyclerView.

customizationButtonView.setOnClickListener {
    val fragmentTransaction = activity.supportFragmentManager.beginTransaction()
    if (customizationFragment==null){
        stack?.let{ stack ->
            fragmentContainer.tag = stack.id.toString()

            val frag = StackCustomizationFragment(stack)
            customizationFragment = frag
            fragmentTransaction.replace(R.id.fragmentContainer, frag, stack.id.toString())
        }
    }
    else{
        customizationFragment?.let { fragmentTransaction.remove(it) }
        customizationFragment = null
    }
    fragmentTransaction.commit()
}

Even the tagging seems to be ignored. Is there another way I can tell the FragmentManager to load the Fragment in the correct R.id.fragmentContainer?

Upvotes: 0

Views: 49

Answers (1)

Francesc
Francesc

Reputation: 29330

You can set an id to your view with

frameLayout.setId(uniqueId)

you would assign an ID to your view in the bind method, based on the position of the item being bound. You could use position + PREDEFINED_OFFSET for instance.

you would then inflate your layout in position + PREDEFINED_OFFSET.

Upvotes: 2

Related Questions