Search code examples
javaandroidandroid-fragmentsandroid-nested-fragment

How to add fragment to existing fragment dynamically?


I want to add a fragment to an existing fragment on a button press (button sits on parent fragment) but I get an error: java.lang.ClassCastException: must implement OnFragmentInteractionListener.

What does that mean and why doesn't any of the example have it?

Parent fragment button press code:

Button interestedButton = (Button) myFragmentView.findViewById(R.id.interestedButton);
interestedButton.setOnClickListener(new View.OnClickListener() {
    InterestedFormFragment interestedFormFragment = new InterestedFormFragment();
    @Override
    public void onClick(View v) {
        FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction().add(R.id.interestedFrag_container, interestedFormFragment, "INTERESTED_FORM");
        fragmentTransaction.commit();
    }
});

Parent fragment XML:

<?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="match_parent"
android:orientation="vertical"
android:background="#FFFFFF"
android:layout_gravity="bottom"
android:id="@+id/buildingPageId">

<LinearLayout
    android:orientation="vertical"
    android:id="@+id/interestedFrag_container"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"/>
...

The "interestedFrag_container" should hold the newly added child fragment.

My parent fragment isinflated and hold the button that should add the child. What am I missing here? Thank you!


Solution

  • Nested fragment are only added since API 17.

    You can use getChildFragmentManager() to manage your nested fragments.