public class BasePresenter<T extends IMvpView> { //IMVpView为总接口,里面没有任何东西
private T t;
public void SetAttachView(T t) {
this.t = t;
}
public T getView() {
return t;
}
}
//httputils类,工具类的使用,避免了只能解析单一对象,想要什么类型的对象,就传入哪个Bean类
public class httputils {
public static <T> void GetDataFormService(String url, final CallBackToPresenter callBackToPresenter, final Class<T> t) {
RequestParams params = new RequestParams();
params.setUri(url);
x.http().get(params, new Callback.CommonCallback<String>() {
@Override
public void onSuccess(String result) {
Gson gson = new Gson();
T t1 = gson.fromJson(result, t);
callBackToPresenter.ToPresenter(t1);
}
@Override
public void onError(Throwable ex, boolean isOnCallback) {
Log.e("Error", "onError: " + ex.getMessage());
}
@Override
public void onCancelled(CancelledException cex) {
}
@Override
public void onFinished() {
}
});
}
public interface CallBackToPresenter<T> {
void ToPresenter(T t);
}
}
public class HomePresenter extends BasePresenter<IHomeView> {//presenter层,作用:从httputils类中拿到数据,并回调回view层
String url = "http://result.eolinker.com/gfGTLlHc049c6b450500b16971f52bd8e83f6b2fed305ab?uri=news";//需要请求的url地址
public <T> void getDataToView(final Class<T> t) {
httputils.GetDataFormService(url, new httputils.CallBackToPresenter<T>() {
@Override
public void ToPresenter(T t1) {
getView().CallBack(t1);//把model层传回来的数据再次传递到view层,由view层做显示处理
}
}, t);
}
}
private void GetDate() {//在activity中的方法
HomePresenter presenter = new HomePresenter(); //首先要拿到HomePresenter 也就是Presenter层的引用
presenter.SetAttachView(this); //这个方法是在basepresenter中的方法,因为homePresenter继承了basePresenter,所以能用HomePresenter中的方法,
// 并把当前acitivity的引用传过去,然后用接口回调,把数据传到acitivity层中进行显示
presenter.getDataToView(HomeBean.class);
}
//IMVpView是一个空接口
public interface IHomeView<T> extends IMvpView {
//成功调用的方法
void CallBack(T t);
//失败调用的方法
//void CallErrorBack(T t);
}