Search code examples
androidandroid-fragmentsmvp

MVP: Best practice to manage Activities and Fragments


I have an Activity with two Fragments. I decided to have one presenter for each "view". So 1 presenter for the main Activity, 1 for the first fragment, and 1 presenter for the second fragment.

I have uses-cases in which I don't know where which code goes.

  • The first is where to manage fragments with fragment manager ? Do I have to do calls like "beginTransaction().add" in the activity or in his presenter ?

  • The second is, when the user tap on a button in the activity, I've to do some things in the current fragment. Do I have to call the presenter of the activity which will call the fragment's method wanted, or directly in the method onClick in the activity I call this fragment's method?

PS: I don't want to use any lib/framework


Solution

  • The first is where to manage fragments with fragment manager ? Do I have to do calls like "beginTransaction().add" in the activity or in his presenter ?

    Everything that is Android API related should be inside the Activity. So, beginTransaction() is a method of the FragmentManager and this is part of the Android API. The Activity is the contract between your app and the operating system. The presenter should not even know that it is used for an Android app. If you press a button inside the Activity for instance it goes like this:

    Inside event handler method which is inside your Activity you do this: Call activityPresenter.onButtonClicked() and it will call activityView.presentWhatTheButtonClickDid()

    The second is, when the user tap on a button in the activity, I've to do some things in the current fragment. Do I have to call the presenter of the activity which will call the fragment's method wanted, or directly in the method onClick in the activity I call this fragment's method?

    You would indirectly call the Fragment method via its presenter.

    Inside event handler method which is inside your Activity: Call activityPresenter.onButtonClicked() and it will call
    fragmentPresenter.onButtonClicked() and it will calls fragmentView.presentResult()

    So, as you see the Activitiy's presenter needs to know the Fragment's presenter.

    *You should not name your presenters with "activity" or "fragment" in its name to keep things abstract. I merely did this for simplicity.