I've been following MVP design pattern provided by Google to refactor my application. I have one MainActivity and many Fragments and it's seems little be messy for me to create activity for every fragment , so i've been thinking to register presenter in fragment. What i'm seeing is that every fragment register it's own presenter, but i'm not sure how much wrong it is... :)
So here is my Presenter:
public class FirstPresenter implements FirstContract.Presenter {
private final FirstContract.View mView;
public FirstPresenter(FirstContract.View view) {
mView = view;
}
@Override
public void start() {
Log.e(TAG, "Start");
}
}
And here is my Fragment:
public class FirstFragment extends Fragment implements FirstContract.View {
private FirstContract.Presenter mPresenter;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container
, Bundle savedInstanceState) {
...
// I register firstFragment's presenter here.
mPresenter = new FirstPresenter(this);
...
So my question is, is this right way? Can i register Presenter into Fragment instead in Activity? And if it is not right way, is there some good example to handle MVP with one activity and multiple fragments?
Thank you guys, BR!
As you can see in Google's samples (https://github.com/googlesamples/android-architecture),
Activities
createPresenters
. AlsoViews
attach toActivity
andPresenters
get views (Fragments
) as parameter.After
Fragment
transaction committed orFragment
(view) state restoredPresenters
get created and takeFragments
(views) as parameter than callmethods of views and
Presenters
get registered to view.I think creating
Presenter
inFragment
is not a good practice. First of all they are separate layers. This is illegal for Separation of concerns. And second, if you create presenter inFragment
, you bind your Presenter's life to view'sLifeCycle
and whenFragment
is destroyed and recreated, you create a new presenter but they're different layers.The model is an interface defining the data to be displayed or otherwise acted upon in the user interface.
The presenter acts upon the model and the view. It retrieves data from repositories (the model), and formats it for display in the view.
The view is a passive interface that displays data (the model) and routes user commands (events) to the presenter to act upon that data.
So
Activity
can act as anoverall controller
which creates thePresenters
andViews
and connect them.If we talk about your question, yes you can register presenter in fragment. But you should avoid creating presenters in fragments which you use as a view.
But there're lot's of different approaches about MVP pattern in Android community like below. https://plus.google.com/communities/114285790907815804707
Why activities are not ui elements? http://www.techyourchance.com/activities-android/