android之MVP开发模式初探

时间:2022-12-23 21:15:13
 最近接触到MVP项目,之前只是听过,没有使用过这种模式进行开发,现在实践了一下感觉的确比一锅粥开发清楚多了,
代码逻辑清晰。我对MVP的了解主要也是看别人的博客,其实我对MVP分别代表什么并不深究,相信大家看一下下面的代码
就会明白MVP是如何使用的。
Model:
public class ListViewMode {
interface DataProvider {
void getdatasuccess(List<String> list);

void getdatafail(String msg);
}

interface DataGetter {
void getdata();
}
}
View:
public class MainActivity extends AppCompatActivity implements ListViewMode.DataProvider {
@Bind(R.id.listview)
ListView listview;
ListViewPresenter presenter;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
initData();
}

private void initData() {
presenter = new ListViewPresenter(this);
presenter.getdata();
}

@Override
public void getdatasuccess(List<String> list) {
listview.setAdapter(new ListViewAdapter(MainActivity.this, list));
}

@Override
public void getdatafail(String msg) {
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
}
}

Presenter:
public class ListViewPresenter implements ListViewMode.DataGetter {
ListViewMode.DataProvider provider;

public ListViewPresenter(ListViewMode.DataProvider dataProvider) {
provider = dataProvider;
}


@Override
public void getdata() {
ArrayList<String> data = new ArrayList<>();
for (int i = 0; i < 40; i++) {
String s = "这是第" + i + "条数据";
data.add(s);
}
if (data.size() > 0) {
provider.getdatasuccess(data);
} else {
provider.getdatafail("获取数据失败");
}
}
}