v:就一个简单的接口,给activity提供数据,activity实现这个接口就可以
所以数据回调都可以用这一个接口
public interface ViewData<T> {
void showProgress();
void hideProgress();
void loadData(T data);
}
m : 数据真正来源,提供数据给p
p需要传递接口过来拿数据,在m的构造方法中将接口传递过来
每个接口都需要一个m,因为传递参数不一样,数据回调不一样
public class ModelMovie {
PresenterListener<MovieResponse<List<Movie>>> listener;
public ModelMovie(PresenterListener<MovieResponse<List<Movie>>> listener){
this.listener = listener;
}
public void getMovies(int start, int end) {
ApiManager.getMovies(start, end).enqueue(new Callback<MovieResponse<List<Movie>>>() {
@Override
public void onResponse(Call<MovieResponse<List<Movie>>> call, Response<MovieResponse<List<Movie>>> response) {
listener.onSuccess(response.body());
}
@Override
public void onFailure(Call<MovieResponse<List<Movie>>> call, Throwable t) {
listener.onFialer(t);
}
});
}
}
p:从m层拿数据,传递数据给v
p要从m层拿数据,所以p需要传递接口给m
v要传递p一个接口
p是直接和activity交互的,所以p层封装m层调用数据的方法,通过调用p层获取数据的方法来触发m层
在p的构造方法中传入v的接口,new m获取m实例,调用它的获取数据的方法
每个接口都要一个p
public class PresenterMovie implements PresenterListener<MovieResponse<List<Movie>>>{
private final ModelMovie modelMovie;
ViewData<MovieResponse<List<Movie>>> viewData;
public PresenterMovie(ViewData<MovieResponse<List<Movie>>> viewData){
modelMovie = new ModelMovie(this);
this.viewData = viewData;
}
public void getMovies(int start,int end){
viewData.showProgress();
modelMovie.getMovies(start,end);
}
@Override
public void onSuccess(MovieResponse<List<Movie>> response) {
viewData.hideProgress();
viewData.loadData(response);
}
@Override
public void onFialer(Throwable e) {
viewData.hideProgress();
}
}
activity:
实现v接口获取数据
只需new p就可以获取数据
public class Activity extends ListActivity implements ViewData<MovieResponse<List<Movie>>> {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PresenterMovie presenterMovie = new PresenterMovie(this);
presenterMovie.getMovies(0,10);
}
@Override
public void showProgress() {
Toast.makeText(this,"showProgress",Toast.LENGTH_SHORT).show();
}
@Override
public void hideProgress() {
Toast.makeText(this,"hideProgress",Toast.LENGTH_SHORT).show();
}
@Override
public void loadData(MovieResponse<List<Movie>> data) {
List<String> titles = new ArrayList<>();
for (Movie m: data.getSubjects()){
titles.add(m.getTitle());
}
ArrayAdapter aa = new ArrayAdapter(this, R.layout.main,titles);
setListAdapter(aa);
}
}