I've been following MVP design pattern provided by Google to refactor my application. I have one MainActivity and many Fragments and it seems little be messy for me to create an activity for every fragment, so I've been thinking to register presenter in fragment. What I'm seeing is that every fragment register its 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 the 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
create Presenters
. Also Views
attach to Activity
and Presenters
get views (Fragments
) as parameter.
After Fragment
transaction committed or Fragment
(view) state restored Presenters
get created and take Fragments
(views) as parameter than call
view.setPresenter(T presenter);
methods of views and Presenters
get registered to view.
I think creating Presenter
in Fragment
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 in Fragment
, you bind your Presenter's life to view's LifeCycle
and when Fragment
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 an overall controller
which creates the Presenters
and Views
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/