How to add a fragment to a layout of a DialogFragment?

最后都变了- 提交于 2019-12-05 09:44:10
Raghav Sharma

After trying a lot, I came to a conclusion that onCreateDialog() doesn't have a view, it just sets a view on calling setView().

That is why on adding dynamic(framelayout tag) or static fragment(fragment tag) in the layout of the dialogfragment gives no parent view or duplicate id error.

To achieve the above, one should use onCreateView with a framelayout tag which can be inflated dynamically. Title and alert buttons are then added to the layout.

R.id.myFragmentHolder is inflated to the dialog's layout, and getFragmentManager() returns the manager for the activity, so it can't find the view.

With nested fragments in API level 17 you can use getChildFragmentManager().

Just be sure that the reports_dialog layout containts a layout whose id myFragmentHolder like this one

<FrameLayout
android:id="@+id/fragment_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" />

Just for reference here, as Brandon mention the correct answer is to use the getChildFragmentManager(), keeping in mind, that android will also restore the state of fragments.

The correct code, to add your first fragment, is:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // if the saved instance isn't null, the fragment state will be restored by android
    if (savedInstanceState == null) {
        getChildFragmentManager().beginTransaction().add(R.id.myFragmentHolder, new ReportsListFragment()).commit();
    }
}

after the view has been added. Later use replace if only one fragment should be shown at the same time.

I would also recommend to call transaction.addToBackStack(null); if the Android back button should be supported.

id of fragment holder in layout is fragmentHolder and you are using myFragmentHolder in code try to replace this by:

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