Search code examples
androidguiceroboguice

Inject dependencies into views with roboguice


Activity fields:

public class MyActivity extends RoboActivity {
    @InjectView(R.id.my_view)
    protected MyView myView;

    @Inject
    private MyDependency myDependency;

    // onCreate etc
}

View fields:

public class MyView extends FrameLayout {
    @Inject
    private MyDependency myDependency;

    // constructors etc
}

The problem is: both myView and myDependency are injected into the activity, but the myDependency is not injected into the view. Why?


Solution

  • Views are instantiated by the Android framework, not by Roboguice. You can use Injector.injectMembers to inject the view's members, but I'd try to avoid Guice dependencies from inside the View.