I have an Android MVP project. I want to keep out any Android references out of the presenter. This way, I can keep UI separated in the Activity/View.
There is a ListView
in the Activity
which uses a custom ArrayList
in the adapter (MyAdapter
). This uses MyModel
objects to populate the ListView
with data.
Now, I'm trying to initialize the adapter and the ListView
.
By doing that on the activity I would end up with something like
`MyAdapter adapter = new MyAdapter<MyModel>(this, R.layout.list_item, items);`
The problem with this is that the Activity
now have access to the Model and has a reference to an ArrayList
of items which I wanted to keep only in the presenter and manage it from there.
I can't move setup the adapter on the Presenter because I would have to share the context from the Activity to the presenter, setup the adapter and pass it back to the Activity. The problem with this is that the presenter now depends on an Android context object (There shouldn't be any Android code in the Presenter part of an MVP Android project).
So the question is what do I do in this case? Where and how do I handle setting up the ArrayAdapter?
You can keep a list of items in the Presenter and then, send it to the Activity when you need to set up the adapter.
I think you can do:
Contract:
public interface ViewContract {
void setupContentList(ArrayList<MyModel> list);
}
public interface PresenterContract {
void onViewCreated();
}
Activity:
public class MainActivity extends Activity implements ViewContract {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
......
mListView = findViewById(R.id.listview);
mPresenter.onViewCreated();
}
public void setupContentList(ArrayList<MyModel> list) {
MyAdapter adapter = new MyAdapter<MyModel>(this, R.layout.list_item, items);
mListView.setAdapter(adapter);
}
}
Presenter:
public class Presenter implements PresenterContract {
public Presenter() {
ArrayList<MyModel> mItems = new ArrayList();
// Add items to the list
}
public void onViewCreated() {
mView.setupContentList(mItems);
}
}