architecture-samples icon indicating copy to clipboard operation
architecture-samples copied to clipboard

MVP with multiple fragments

Open cfva14 opened this issue 9 years ago • 2 comments

How do you handle multiple fragments in a single activity? Example, steps for registering a new user in a login Activity. Because currently we need the fragment for the presenter, but what happens when you have multiple fragments?

cfva14 avatar Nov 29 '17 05:11 cfva14

One way of doing this is to have all the registration fragments controlled by the same presenter: In your LoginActivity you would have instances of the fragments that you want to show in every step of the registration process and you would create a method like showView(String fragmentId) in this activity. This method just replaces a fragment with another.

Or for a more testable code, create an interface like this:

public interface SwappableActivity {
   void showView(String fragmentId);
}

And make LoginActivity implement that interface.

Then on LoginActivity's onCreate method, you would pass the instance of the activity to the presenter and also the fragments instances. That way the presenter will have access to the showView(String fragmentId) (so you can swap your fragments) and still control the behaviour of those fragments.

But keep in mind that this solution is practical when you don't have a lot of logic to handle in each fragment. If you do, I recommend using several presenters to keep the separation of concerns and make your code easier to maintain.

fjoshuajr avatar Nov 29 '17 11:11 fjoshuajr

Feel free to move this discussion on stackoverflow for traceability.

florina-muntenescu avatar Nov 29 '17 12:11 florina-muntenescu