MVP的实现,后续更新mvp和databinding结合

本文详细介绍了一种流行的软件架构模式——MVP(Model-View-Presenter)模式。文章深入讲解了MVP模式的基本概念、各组成部分的功能及其实现方式,并通过具体的代码示例展示了如何在Android应用中实现这一模式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这里写图片描述

上图是界面和运行效果,mvp的结构图如下:
这里写图片描述这里写图片描述

presenter类主要处理业务逻辑,view通过接口来和presenter交互减少耦合度,mode主要是存储数据和提供数据。

—–presenter—–
presenter代码

/**
 * 业务逻辑顶层父类
 * Created by Administrator on 2017/9/2.
 */

 public class BasePresenter {

     Context mContext;

   public void onAttached(Context mContext) {
        this.mContext = mContext;
    }


    public void onCreat() {
    }


    public void onPause() {
    }

    public void onResume() {
    }

    public void onDestory() {
        System.out.println("=test=BasePresenter=onDestory");
        if (mContext != null) {
            mContext = null;
        }
    }
}

**
 * mainActivity的逻辑处理类
 * Created by Administrator on 2017/9/2.
 */

 public class MainViewPresenter extends BasePresenter implements HttpUtil.HttpResponse {
    //创建构造函数,要求是实现了mainViewInterface的子类
    //view和presenter的对接扣

    String netUrl = "http://tcc.taobao.com/cc/json/mobile_tel_segment.htm";

    public MainView mainView;
    public PhoneInfo phoneInfo;

     public MainViewPresenter(MainView mainView) {
        this.mainView = mainView;
    }
    //逻辑处理,获取数据,点击就事件等

    //获取网络数据,传入参数
    public void fetchDataFromNet(String phoneNumber) {
        //校验或者包装参数
        if (phoneNumber.length() != 11) {
            mainView.showToast("请输入正确手机号");
            return;
        }

        mainView.showLoading();
        //下面是okhhtp开始请求数据
        HttpUtil httpUtil = new HttpUtil();
        HashMap<String, String> map = new HashMap<>();
        map.put("tel", phoneNumber);
        httpUtil.sendHttpGet(map, netUrl);
        httpUtil.setHttpResponse(this);
    }

    @Override
    public void onFailed(String failure) {
        mainView.showToast(failure);
        mainView.hidenLoading();
    }

    @Override
    public void onSuccess(String result) {
        mainView.hidenLoading();
        //数据解析也在presenter
        try {
            result=result.substring(result.indexOf("{"),result.length());
            phoneInfo=new Gson().fromJson(result,PhoneInfo.class);
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
            mainView.showToast("返回结果解析异常");
        }
        //刷新UI
        mainView.updataCurrentView();
    }

    public PhoneInfo getPhoneInfo(){
        return phoneInfo;
    }

}

—–view—–
view层

/**
 * view的顶级父类,给p提供交互
 * Created by Administrator on 2017/9/2.
 */

public interface BaseView {

    void showLoading();
    void hidenLoading();
}
/**
 * mainView的接口,v和p都是通过infterface来交互解耦
 * Created by Administrator on 2017/9/2.
 */

public interface MainView  extends BaseView {
    //view的方法太多,抽取父类,都是给pren层的
    void showToast(String msg);
    void updataCurrentView();//可以传入参数的
}


-----activity的代码-----

public class MainActivity extends AppCompatActivity implements View.OnClickListener,MainView {


    private MainViewPresenter mainViewPresenter;
    private ActivityMainBinding mainBinding;
    private ProgressDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        //将整个view层都传出去
        mainBinding.btnQuery.setOnClickListener(this);
        mainViewPresenter = new MainViewPresenter(this);
        mainViewPresenter.onAttached(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mainViewPresenter.onDestory();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_query:
                String phone=mainBinding.editPhone.getText().toString().trim();
                mainViewPresenter.fetchDataFromNet(phone);
                break;
        }
    }

    @Override
    public void showLoading() {
        dialog = new ProgressDialog(this);
        dialog.show();

    }

    @Override
    public void hidenLoading() {
        if (dialog!=null&&dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    @Override
    public void showToast(String msg) {
        Toast.makeText(this,msg,Toast.LENGTH_SHORT).show();
    }

    @Override
    public void updataCurrentView() {
        PhoneInfo phoneInfo = mainViewPresenter.getPhoneInfo();
        mainBinding.tvPhone.setText("手机号:"+phoneInfo.getTelString());
        mainBinding.tvProvince.setText("省份:"+phoneInfo.getProvince());
        mainBinding.tvSeller.setText("运营商:"+phoneInfo.getCatName());
        mainBinding.tvSeller2.setText("归属运营商:"+phoneInfo.getCarrier());

    }
}

最后是通用的http请求类

/**
 * 定义通用http请求网络类
 * Created by Administrator on 2017/9/2.
 */

public class HttpUtil {

    private final OkHttpClient client = new OkHttpClient();
    private String url;
    private Map<String, String> params;
    private Handler handler = new Handler(Looper.getMainLooper());

    public void setHttpResponse(HttpResponse httpResponse) {
        this.httpResponse = httpResponse;
    }

    //设置接口将结果传送回去
    private HttpResponse httpResponse;

    public interface HttpResponse {
        //失败请求回调
        void onFailed(String failure);

        //成功请求回调
        void onSuccess(String result);
    }

    /**
     * Post请求
     */
    public void sendHttpPost(Map<String, String> param, String netUrl) {
        doHttpNet(param, netUrl, true);
    }

    /**
     * Get请求
     */
    public void sendHttpGet(Map<String, String> param, String netUrl) {
        doHttpNet(param, netUrl, false);
    }

    private void doHttpNet(Map<String, String> param, String netUrl, boolean isPost) {
        url = netUrl;
        params = param;
        runHttp(isPost);
    }

    private void runHttp(boolean isPost) {
        Request request = creatRequest(isPost);
        //请求头弄完在 直接发送请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                if (httpResponse != null) {
                    //回调是在子线程,而UI是在主线程
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            httpResponse.onFailed(e.toString());
                        }
                    });
                }
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                if (httpResponse != null) {
                    final String result = response.body().string();
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (response.isSuccessful()) {
                                //请求成功
                                httpResponse.onSuccess(result);
                            }else{
                                httpResponse.onFailed(result);
                            }
                        }
                    });
                }
            }
        });
    }


    /**
     * 创建requst
     */
    private Request creatRequest(boolean isPost) {
        Request request;
        if (isPost) {
            //Post请求
            MultipartBody.Builder multipartBody = new MultipartBody.Builder();
            multipartBody.setType(MultipartBody.FORM);//表单形式提交请求
            //遍历map获取参数
            Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, String> next = iterator.next();
                multipartBody.addFormDataPart(next.getKey(), next.getValue());
            }
            //创建请求
            request = new Request.Builder().url(url).post(multipartBody.build()).build();

        } else {
            //Get请求,只是拼接参数和网址
            Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator();
            StringBuilder strBuilder = new StringBuilder(url + "?");//这里先加进去
            while (iterator.hasNext()) {
                Map.Entry<String, String> next = iterator.next();
                strBuilder.append(next.getKey() + "=" + next.getValue() + "&");
            }
            //最后祛除对于的一个“&”符号
            String str = strBuilder.toString().substring(0, strBuilder.length() - 1);
            request = new Request.Builder().url(str).build();
            System.out.println("==test==" + str);
        }

        return request;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值