【发布时间】:2014-04-16 19:59:49
【问题描述】:
我想尝试将 MVP 模式用于我正在编写的简单 Android 应用程序。这是我第一次使用 MVP 模式,因为我还在学习中,所以请温柔;)
我有一个片段,我想与 4 位不同的演示者一起使用。我的问题是,如何将不同的演示者传递给每个实例?
我希望喜欢将演示者传递给构造函数,但是当 Android 重新创建片段时,它将调用默认构造函数。这是否意味着它将不再包含对演示者的引用?
如果是这样,我还能如何传递演示者?
我在下面包含了一些我想做的伪代码。请注意,我只是直接在浏览器中输入了此内容,因此可能会出现一些愚蠢的错误,但希望您能大致了解我的意思。
我的 2 个界面:
public interface IClickableListPresenter {
ListAdapter createListAdapter();
void onListItemClick(int position);
}
public interface ITabbable {
String getTitle();
Fragment getFragment();
}
2 个示例演示者:
public class ArtistPresenter implements IClickableListPresenter {
public ListAdapter createListAdapter(){
// Create a ListAdapter containing a list of artists
}
public void onListItemClick(int position){
// Handle the click event
}
}
public class TitlePresenter implements IClickableListPresenter {
public ListAdapter createListAdapter(){
// Create a ListAdapter containing a list of song titles
}
public void onListItemClick(int position){
// Handle the click event in a completely different way
// to the ArtistPresenter
}
}
我的片段:
public class ClickableListFragment extends ListFragment
implements ITabbable {
private IClickableListPresenter presenter;
private String title;
// What can I do instead of this constructor?
public ClickableListFragment(
String title, IClickableListPresenter presenter){
this.title = title;
this.presenter = presenter;
}
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setListAdapter(presenter.createListAdapter());
}
@Override
public void onListItemClick(ListView l, View v, int position, long id){
presenter.onListItemClick(position);
}
public Fragment getFragment(){
return this;
}
public String getTitle(){
return title;
}
}
最后,实例化片段的类:
public class TabsPagerAdapter extends FragmentPagerAdapter{
private ITabbable tabs[] = {
new ClickableListFragment("Artist", new ArtistPresenter()),
new ClickableListFragment("Title", new TitlePresenter()),
//...
};
//...
}
【问题讨论】: