Android: Add fragments by looking up container with tag instead of ID

泪湿孤枕 提交于 2020-01-30 08:19:26

问题


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:


Fragments 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 Fragments 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!