mvp封装

作者: Android纯白 | 来源:发表于2019-01-24 11:05 被阅读0次

    什么是mvp,我就不多说,mvp作用就是用一个类作为桥梁,然后进行数据和view的一些交互。通过接口进行相互交流。
    mvp主要是由3部分组成(view,presenter,model),这里封装我舍弃了model,数据处理直接放在presenter上,然后通过接口实现了ui和view的交互(原本的交互是放在presenter上处理)

    创建view接口类和presenter接口类(model接口类)

    //view的接口类
     public interface BaseView {
        Context getContext();
    }
    
    //presenter
    public interface BasePresenter<V extends BaseView>  {
        //添加view
        void addView(V view);
       //删除view
        void deleteView();
    }
    

    实现presenter接口

    -通过addview拿到view的对象,

    public class PresenterImp<V extends BaseView> implements BasePresenter<V> {
        protected V mView;
        private WeakReference<V> vWeakReference;
        @Override
        public void addView(V view) {
            vWeakReference = new WeakReference<>(view);
            mView=vWeakReference.get();
        }
        @Override
        public void deleteView() {
            if (vWeakReference!=null)
            {
                vWeakReference.clear();
                mView=null;
            }
        }
    }
    

    实现BaseView接口

    public abstract class MvpActivity<DB extends ViewDataBinding,P extends PresenterImp>
            extends BaseActivity<DB> implements BaseView {
    
        protected P mPresenter;
        @Override
        public Context getContext() {
            return this;
        }
    
        //创建PresenterImp对象
        protected abstract P creartPresenter();
    
        @Override
        protected void beforeView() {
            super.beforeView();
            mPresenter= creartPresenter();
            if (mPresenter!=null) {
                mPresenter.addView(this);
            }
        }
    
        @Override
        protected void onDestroy() {
            super.onDestroy();
            if (mPresenter!=null) {
                mPresenter.deleteView();
            }
        }
    }
    

    举栗子

    //接口管理类
    public class GuideContract {
        interface View extends BaseView
        {
    
        }
    
        interface Presenter extends BasePresenter<View>
        {
    
        }
    }
    
    //数据类
    public class GuidePresenter extends PresenterImp<GuideContract.View> implements GuideContract.Presenter{
    
    }
    
    //ui类
    public class GuideActivity extends MvpActivity<ActivityGuideBinding,GuidePresenter>
            implements GuideContract.View{}
    

    相关文章

      网友评论

          本文标题:mvp封装

          本文链接:https://www.haomeiwen.com/subject/rskyjqtx.html