问题
I am creating multiple instances of a fragment with a for loop. Within each fragment, I need to add another set of child fragments. In doing that, I need to find the correct container. If I use the ID of the container, all the child fragments gets added to the first parent fragment, instead of their own parent fragments.
In my main fragment:
for (....) {
ParentFragment parentFragment = new ParentFragment();
parentFragment.setSomeData(data);
fragmentTransaction.add(R.id.main_fragment_container, parentFragment, data);
}
fragmentTransaction.commit();
Now I have N Parent Fragments.
Within each ParentFragment:
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
ChildFragment childFragment = new ChildFragment();
childFragment.setSomeData(data);
fragmentTransaction.add(R.id.parent_fragment_container, childFragment).commit();
}
The issue is, all instances of ChildFragment
gets added to the first ParentFragment because "R.id.parent_fragment_container" is a constant for all ParentFragment. It doesn't change for each instance of ParentFragment.
Because I have unique tag for each instance of ParentFragment, can I lookup the container using this tag instead of R.id.parent_fragment_container
?
XML definitions:
fragment_main.xml:
<LinearLayout
android:id="@+id/main_fragment_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
fragment_parent.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/parent_fragment_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
回答1:
Fragment
s inside another Fragment
should be handled with that parent Fragment
's FragmentManager
– obtained with getChildFragmentManager()
– rather than the Activity
's FragmentManager
.
The child FragmentManager
will search only the parent Fragment
's View
for the given container ID, so you won't end up with all of the child Fragment
s in the first found container, as was happening when the Activity
's FragmentManager
just used the first parent_fragment_container
it would find in the Activity
's overall hierarchy.
来源:https://stackoverflow.com/questions/50013046/android-add-fragments-by-looking-up-container-with-tag-instead-of-id