I have a custom view extending a TextView
. Where should I call my component to inject the view?
component.inject(customTextView);
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 {}