Jason Crosby Jason Crosby - 1 year ago 80
Android Question

Activity And Fragment Interaction

I have an

with multiple
s. I want to show a
or open another
from one of the
s. I know that an
should be the one tasked with opening
s so instead I have tried a couple things.


I tried to use
and cast it so I can call a method in the
to show a
however this creates a dependency in the
with the
and I would like to avoid adding a dependency if possible.


Next I tried a listener to notify the
that it should show a
. So I created a class in the
to implement the listener interface. But I had problems because I had to use
New MyActivity().new Listener();
and it would throw an
when I tried to use
since this instance of the
is not initialized.


I then tried to have the
implement the listener directly which works because then I am only creating a dependency with the listener and not the Activity. However now I am getting to the point where my
will be implementing 2 - 4 different interfaces which is making me hesitant because it will severely reduce cohesion.

So any way I have tried I seem to be running into a brick wall and creating dependancies I'm not sure I need to be creating. Am I screwed and have to go with one of these options? If so which option would be best? Any help or suggestions are are greatly appreciated.

Answer Source

Personally I would say that fragments should be thought as reusable and modular components. So in order to provide this re-usability, fragments shouldn't know much about their parent activities. But in return activities must know about fragments they are holding.

So, the first option should never be considered in my opinion for the dependency reason you mentioned causing a very highly coupled code.

About the second option, fragments may delegate any application flow or UI related decisions (showing a new fragment, deciding what to do when a fragment specific event is triggered etc..) to their parent activities. So your listeners/callbacks should be fragment specific and thus they should be declared in fragments. And the activities holding these fragments should implement these interfaces and decide what to do.

So for me the third option makes more sense. I believe that activities are more readable in terms of what they are holding and doing on specific callbacks. But yes you are right your activity might become a god object.

Maybe you can check Square's Otto project if you don't want to implement several interfaces. It's basically an event bus.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download