'FragmentManager replace Fragment to wrong FragmentContainerView ID when using include same layouts
I have a layout named fragment_item.xml contain a FragmentContainerView. I set its id to fragmentContainerFront.
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingTop="@dimen/padding_regular"
android:paddingBottom="@dimen/padding_regular">
<androidx.fragment.app.FragmentContainerView
android:id="@+id/fragmentContainerFront"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
By reusing it, i used <include> tag to duplicate it.
<include
android:id="@+id/container1"
layout="@layout/fragment_item" />
<include
android:id="@+id/container2"
layout="@layout/fragment_item" />
In fragment, I have a function that create Fragments and replace it into FragmentContainerView using fragmentManager.replace
inflateFragmentToContainer(
binding.container1.fragmentContainerFront.id,
fragmentFrontA
)
inflateFragmentToContainer(
binding.container2.fragmentContainerFront.id,
fragmentFrontB
)
private fun inflateFragmentToContainer(@IdRes id: Int, fragment: Fragment) {
childFragmentManager.beginTransaction()
.replace(id, fragment).commit()
}
The weird point is, both functions inflateFragmentToContainer, in childFragmentManager will replace same FragmentContainerView in container1.
My expectation is first function will replace container1's FragmentContainerView, 2nd function will replace container2's FragmentContainerView and so on.
I tried to debug, when trying to get FragmentContainerView, fragmentContainerFront in both include return same ID. Is that why childFragmentManager replace on the same layout. Not separately?
In my mind, when including with different ID, it will be different.
If I clone fragment_item.xml and change the ID of FragmentContainerView, it will do correctly what I want to do. But it is hard to duplicate instead of cloning and modify the ID.
Any workaround for this? Thanks.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
