Dagger 2.10/2.11 injecting Activity failing

前端 未结 1 1722
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-06 09:39

I have been trying to, unsuccessfully, inject the Activity in a class ViewUtils. I have followed a couple of different posts but I can\'t seem to understand what am I missing in

1条回答
  •  长情又很酷
    2021-02-06 10:37

    As specified in dagger android documentation:

    Pro-tip: If your subcomponent and its builder have no other methods or supertypes than the ones mentioned in step #2, you can use @ContributesAndroidInjector to generate them for you. Instead of steps 2 and 3, add an abstract module method that returns your activity, annotate it with @ContributesAndroidInjector, and specify the modules you want to install into the subcomponent. If the subcomponent needs scopes, apply the scope annotations to the method as well.

    Thus, we can get rid of LoginSubcomponent and perform following changes in ActivityBindingModule:

    
    
        @Module
        public abstract class ActivityBindingModule {
    
            @ActivityScope
            @ContributesAndroidInjector(modules = LoginActivityModule.class)
            abstract LoginActivity loginActivity();
        }
    
    
    

    LoginActivityModule.java

    
    
        @Module
        abstract class LoginActivityModule {
    
            @Binds
            abstract Activity bindActivity(LoginActivity activity);
    
            @Provides
            @ActivityScope
            static ViewUtils viewUtils(Activity activity) {
                return new ViewUtils(activity);
            }
        }
    
    
    

    Your custom application class:

    
    
        public class MyApp extends DaggerApplication {
    
            @Inject
            DispatchingAndroidInjector dispatchingActivityInjector;
    
            @Override
            protected AndroidInjector applicationInjector() {
                return DaggerAppComponent.builder().create(this);
            }
    
        }
    
    
    

    0 讨论(0)
提交回复
热议问题