knaecke knaecke - 5 months ago 37
Android Question

How to display an existing ListFragment in a DialogFragment

I have the following problem:

I have an exisiting

ListFragment
, but I would like to display this as a dialog.

My first approach was to create a
DialogFragment
which has to
ListFragment
inside of it, but appearently it is currently not possible to put fragments in fragments.

Extending
DialogFragment
instead of
ListFragment
is also not possible, because of the heavy use of
ListFragment
methods.

Is there an easy way to do this?

Answer

What works for me is

1) in xml layout for your DialogFragment called, let's say, DialogFragmentwWithListFragment specify ListFragment class
E.g. dialog_fragment_with_list_fragment.xml :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <fragment
             android:id="@+id/flContent"
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             android:padding = "10dp"
             class="com.xxx.yyy.DialogFragmentwWithListFragment " />
</LinearLayout>

2) in DialogFragmentwWithListFragment inflate dialog_fragment_with_list_fragment.xml

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.dialog_fragment_with_list_fragment, null);
}

3) invoke DialogFragmentwWithListFragment as regular DialogFragment:

 DialogFragmentwWithListFragment dialogFragment = DialogFragmentwWithListFragment  .newInstance();
 dialogFragment.setRetainInstance(true);
 dialogFragment.show(getFragmentManager(), "tag");


Hope, it helps.