L. Gangemi
L. Gangemi

Reputation: 3290

Android Display 2 fragments inside another one

I've got an Application with a MainActivity with a Navigation Drawer Menu.

Inside the MainActivity View I've got a Frame layout which takes the whole space.

When the user selects something from the menu I call a method which handles the fragments transaction inside the Frame Layout.

My MainActivity is the Fragment manager and from here I can handle all the changes I want and I can handle the communications between the fragments.

Here's the problem:

In one of my Fragment I'd like to show 2 new fragments, one with a PieChart and one with the data.

I could have done only one Fragment with all inside its view but I'd like to use a modular managing way.

So, first of all I created 1 fragment, the Container one (we can call it A).

In its view I put the fragment B and fragment C, directly from Xml.

In fragment B I've got the PieChart, HERE I call the methods to download data from a database, and then I put this data inside the chart.

I wrote a simple Interface which contains a method which is called when the user interacts with the chart; it builds an object with the selected data.

My target is to send this data to Fragment A and then pass them to Fragment C, so that the user can see what is he selecting.

In Fragment A I've Implemented the Fragment B interface, then I set up this code inside OnAttach of B:

 @Override
public void onAttach(Context context) {
    super.onAttach(context);
    try {
        Interface = (InterfaceB) context;
    } catch (ClassCastException e) {
        throw new ClassCastException(context.toString()
                + " must implement InterfaceB");
    }
}

Everything seems to works, but in the moment that Fragment A is created, OnAttach of B is called, and the context which arrives refers to MainActivity and not to Fragment A.

This causes a crash.

Upvotes: 0

Views: 73

Answers (1)

Ufkoku
Ufkoku

Reputation: 2638

Fragment is not an instance of Context, so it is impossible to pass it to onAttach(Context Context) anyway.

There are two ways how you can do what you want.

1) Use onAttachFragment(Fragment fragment) inside fragment A, and catch events when fragments B and C are attached;

2) Use getParentFragment() inside fragments B and C, to access A.

Upvotes: 1

Related Questions