MVP基类使用介绍

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);
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值