MVP框架 简单使用

//关于接口地址的封装
public class APIMain {
    public static String mainUrl = "https://www.zhaoapi.cn/ad/getAd";
}
//view层
  
public class MainActivity extends AppCompatActivity implements IMainView{

    private Presenter presenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

       /* mvp
       * //当要获取数据的时候,通知presenter,,,presenter再去通知model获取数据
        //view层有一个presenter的引用,,,,presenter要有model的应用
        //model获取的道具之后,传给presenter...presnter再去传给view
        //接口回调....model里面有presenter实现了接口的引用....presenter需要有view实现了接口的引用
        //view层有一个presenter的引用
       * */
        presenter = new Presenter(this);
        presenter.getData(APIMain.mainUrl);



    }

    @Override
    public void onSuccess(final DataDataBean dataBean) {
        //数据拿回来解析
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(MainActivity.this,dataBean.getData().get(0).getTitle(),Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onError() {

    }
}
------------------接口-----------------
public interface IMainView {
    void onSuccess(DataDataBean dataBean);
    void onError();

}
//presenter层
public class Presenter implements IMainP{
       private IMainView iMainView;

    public Presenter(IMainView iMainView) {
        this.iMainView = iMainView;
    }

    private ModelImp modelImp;

    public void getData(String mainUrl) {
        //通知model去解析数据
        modelImp = new ModelImp(this);

          modelImp.getData(mainUrl);
    }


    @Override
    public void onSuccess(DataDataBean dataBean) {
      iMainView.onSuccess(dataBean);
    }

    @Override
    public void onError() {

    }
}
----------------接口-----------
public interface IMainP {
    void onSuccess(DataDataBean dataBean);
    void onError();
}
//model层

public class ModelImp {
    private IMainP iMainP;

    public ModelImp(IMainP iMainP) {
        this.iMainP = iMainP;
    }

    //解析数据的方法
    public void getData(String mainUrl) {
        OkHttpClient okhttp=new OkHttpClient();
        Request request = new Request.Builder()
                .url(mainUrl)
                .build();
     okhttp.newCall(request).enqueue(new Callback() {
         @Override
         public void onFailure(Call call, IOException e) {

         }

         @Override
         public void onResponse(Call call, Response response) throws IOException {
         if(response.isSuccessful()){
             String string = response.body().string();
             DataDataBean dataDataBean = new Gson().fromJson(string, DataDataBean.class);
                  //通过接口回调  将解析出来的信息返回去
                 iMainP.onSuccess(dataDataBean);
         }
         }
     });

    }
}




你可能感兴趣的:(MVP框架 简单使用)