hi i am currently using roboguice as we know, we can use annotation to get class injected such as
@InjectView(R.id.list)ListView x
the @inj
You can inject a custom class simply using the @Inject
annotation, but the injected class must satisfy one of the following conditions:
The easiest way is obviously to use a default constructor. If you must have arguments in your constructor, it must be injected :
public class CustomClass {
@Inject
public CustomClass(Context context, Other other) {
...
}
}
Notice the @Inject
annotation on the constructor. The class of each argument must also be injectable by RoboGuice. Several injections for Android classes are provided out of the box by RoboGuice (for example Context
). Injections provided by RoboGuice
If you create the instance of your custom class with RoboGuice (for example with the @Inject
annotation), all the fields marked with @Inject
will be injected automatically.
If you want to use new CustomClass()
, you'll have to do the injection yourself:
public class CustomClass {
@Inject
Other other;
Foo foo;
public CustomClass(Context context) {
final RoboInjector injector = RoboGuice.getInjector(context);
// This will inject all fields marked with the @Inject annotation
injector.injectMembersWithoutViews(this);
// This will create an instance of Foo
foo = injector.getInstance(Foo.class);
}
}
Note that you have to pass a Context
to your constructor to be able to get the injector.