View dependency injection with dagger 2

前端 未结 3 926
伪装坚强ぢ
伪装坚强ぢ 2021-02-09 05:09

I have a custom view extending a TextView. Where should I call my component to inject the view?

component.inject(customTextView);
3条回答
  •  醉话见心
    2021-02-09 05:45

    UPDATE: Since 2.10 version of Dagger this answer is invalid.

    Custom view:

    public class CustomView extends View {
        @Inject
        AnyObject anyObject;
    
        public CustomView(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        @Override
        protected void onFinishInflate() {
            super.onFinishInflate();
            MainActivity mainActivity = (MainActivity) getContext();
            mainActivity.getComponent().inject(CustomView.this);
        }
    }
    

    Activity:

    ActivityComponent mComponent;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mComponent = DaggerActivityComponent.builder()
                        .appComponent(getApp().getAppComponent())
                        .activityModule(new ActivityModule(MainActivity.this))
                        .build();
        mComponent.inject(MainActivity.this);
        ...
    }
    
    public ActivityComponent getComponent() {
        return mComponent;
    }
    

    Dagger2 component with Activity scope:

    @ActivityScope
    @Component(dependencies = AppComponent.class, modules = {ActivityModule.class})
    public interface ActivityComponent extends AppComponent {
    
        void inject(MainActivity mainActivity);
        void inject(CustomView customView);
    }
    

    Scope:

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

提交回复
热议问题