0

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?

1
  • I found out that placing fragments inside the ViewHolder is a bad idea. When updating the data inside Room the RecyclerView frequently changes which ViewHolder gets bound to which item.
    – Christian
    Jun 20, 2019 at 7:25

1 Answer 1

2

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.

2
  • I'm not sure what you mean with inflate, do I have to call the normal inflate method on an inflater or can I work with the transactions?
    – Christian
    Jun 17, 2019 at 16:13
  • I mean inflating your fragment into the container, with fragmentManager.replace(position + PREDEFINED_ID, fragment, tag)
    – Francesc
    Jun 17, 2019 at 16:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.