美文网首页Android-Dagger2
Dagger 2 与MVP的简单使用

Dagger 2 与MVP的简单使用

作者: 鹅鹅鹅曲项向天歌呀 | 来源:发表于2019-05-05 15:15 被阅读26次

    上一篇已经说过了Dagger 2 的基本使用,局部单利和全局单利的使用,
    Dagger 2 基本使用,局部单例,全局单例
    这边文章说一下,Dagger 2 和MVP的使用方法:

    我们来模拟登陆的功能哈,我写的比较简单,但是很容易看出来,使用方法以及流程,其他的业务功能,自行添加吧,套路都是一样的.

    此项目github地址: https://github.com/Mchunyan/DaggerTest

    1.1 创建 View

    public interface IView {
        Context getContext();
    }
    

    1.2 创建 Presenter
     1、需要用注解 @Inject (Annotation) 来标注目标类中依赖类的实例对象
     2、同样用注解 @Inject (Annotation) 来标注所依赖的其他类的 构造函数。

    public class LoginPresenter {
        private IView iView;
    
        @Inject
        public LoginPresenter(IView iView) {
            this.iView = iView;
        }
    
        public void loginAction(String userName) {
            Toast.makeText(iView.getContext(), userName + ":登录成功....", Toast.LENGTH_SHORT).show();
        }
    }
    

    ** 1.3 自定义Scope**
    scope是用来标注作用范围,作用域,在provider方法写上,这个注解application一般是全局单例模式的,所以Socope用dagger2自带的Singleton就好了.
    其他的 Socope自己定义就好

    @Scope
    @Retention(RetentionPolicy.RUNTIME)
    public @interface BaseScope {
    }
    

    1.4 创建 Moudule

    @Module
    public class LoginModule {
        private IView iView;
    
        public LoginModule(IView iView) {
            this.iView = iView;
        }
    
        @Provides
        @BaseScope
        public IView providesIView() {
            return iView;
        }
    }
    

    1.5 创建Component

    @BaseScope
    @Component(modules = LoginModule.class)
    public interface LoginComponent {
        void join(LoginActivity loginActivity);
    }
    

    1.6 创建 LoginActivity

    public class LoginActivity extends AppCompatActivity implements IView {
        @Inject
        LoginPresenter loginPresenter;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_login);
            DaggerLoginComponent.builder().loginModule(new LoginModule(this)).build().join(this);
        }
    
        @Override
        public Context getContext() {
            return this;
        }
    
        public void 登录(View view) {
            loginPresenter.loginAction("小明");
        }
    }
    

    好了,一个简单的Dagger 2 + MVP 的功能就实现啦~ 就不上图了,就一个页面,一个按钮,没了~

    github地址: https://github.com/Mchunyan/DaggerTest

    开心.jpg

    ------------------------THE END---------------------

    相关文章

      网友评论

        本文标题:Dagger 2 与MVP的简单使用

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