簡易MVP實現

M層獲取數據json

public class Model implements ModelInf {
    @Override
    public void getDate(final Handler handler) {
        OkHttpClient okHttpClient = OkHttpUtil.getInstance();
        Request request = new Request.Builder().url("http://172.16.45.43:8080/first_page.json").build();
                okHttpClient.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String string = response.body().string();
                handler.obtainMessage(100,string).sendToTarget();
            }
        });
    }
}

M接口提供別人調用ide

public interface ModelInf {
    public void getDate(Handler handler);
}

V獲取數據 來更新UI(數據類型能夠多種類型)ui

public interface ViewInf {
    public void upDate(List<Bean.ResultBean.DataBean> list);
}

P層鏈接M.V橋樑this

public interface PresenterInf {
    public void ViewToModel();
}
public class Presenter implements PresenterInf {
    //建立M.V層對象
    private ModelInf modelInf;
    private ViewInf viewInf;
    public Presenter(MainActivity activity) {
        this.modelInf = new Model();
        this.viewInf = activity;
    }
    @Override
    public void ViewToModel() {
        //獲取M層傳遞數據
        modelInf.getDate(handler);
    }
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String s = (String) msg.obj;
            Gson gson = new Gson();

            Bean bean = gson.fromJson(s, Bean.class);
            List<Bean.ResultBean.DataBean> data = bean.getResult().getData();
            //傳遞給V層
            viewInf.upDate(data);
        }
    };
}

實現V層接口實現方法拿到數據url

MainActivity implements ViewInf對象

相關文章
相關標籤/搜索