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 @inject notation works, because i extend from RoboActivity, or any Robo class
my question is if i want to inject a custom class, called
public class CustomUtilManager {
}
i want to be able to Inject it in say RoboActivity
@Inject CustomUtilMananger
how do i do it?
my second question is, if i have a class, that is not subclass of any Robo* class
say
public class MyOwnClass {
}
how do i get the injector and inject another injectable class, such as CustomUtilManager
i.e. how can i say
public class MyOwnClass {
@Inject CustomUtilManager customUtilManager;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With