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

Ajith Memana picture Ajith Memana · Jan 21, 2014 · Viewed 8.8k times · Source

I am having a custom DialogFragment which contains a layout, some UI elements, and a Fragment holder layout. What I need to do is inflate a Content fragment into the holder layout and provide a navigation inside that. On clicking a button inside the added fragment the view will navigate to another view. The fragment will be replaced by another one in the same holder i.e. the contentFragment1 will show some data and on clicking a preview button there will replace contentFragment1 with contentFragment2. I read somewhere that you cannot replace a fragment hardcoded to the xml with another one. So I am trying to add the contentFragment1 to the viewholder from the onActivityCreated() of the dialog fragment. But I am getting an error that the resource pointed by R.id.fragmentHolder not found. What could be the possible reason?

Here is my code for the DialogFragment:

public class MyDialog extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    Dialog customDialog = new Dialog(getActivity());
    customDialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
    customDialog.setContentView(R.layout.reports_dialog);
    return customDialog;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    android.app.FragmentTransaction fragmentTransaction =getFragmentManager().beginTransaction();
    fragmentTransaction.add(R.id.myFragmentHolder, new ReportsListFragment());
    fragmentTransaction.commit();
    super.onActivityCreated(savedInstanceState);
}

enter image description here

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="400dp"
    android:background="@android:color/transparent" >


    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:text="This is my header text view for the Dialog"
        android:textSize="18sp" />

<RelativeLayout
    android:id="@+id/myFragmentHolder"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/headerlayout" >

</RelativeLayout>

Answer

Raghav Sharma picture Raghav Sharma · Jun 17, 2015

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.