In the previous article, we briefly introduced the use of roboguice ([6] use of the injection framework roboguice :( singletons and contextsingletons). Let's take a look at the binding ).
(1): using custom binding, We can bind a class or an interface to a subclass, instance or content provider (provinders ).
Now let's assume that:
public interface IFoo {}public class Foo implements IFoo {}
This custom binding allows you to bind an interface ifoo to the class Foo, and then create a foo instance for each annotation (@ inject ifoo.
public class MyActivity extends RoboActivity { //How to tell RoboGuice to inject an instance of Foo ? @Inject IFoo foo;}
(2): custom binding:
For custom binding, we need to create our own module (s). It is easy to create modules from roboguice 2.0.
①: Register modules in androidmanifset. xml
②: Create a class that inherits abstractmodule
2.1: Register modules in androidmanifset. xml
In androidmanifset. XML, add some meta-data tag fields and modules full names to the application tag, as shown below:
<application ...> <meta-data android:name="roboguice.modules" android:value="com.example.MyModule,com.example.MyModule2" /> </application>
2.2: Create a class that inherits abstractmodule
Each module must be registered before it is created. All of these modules are accessed through reflection. See the following instance code:
package com.example;public class MyModule extends AbstractModule { //a default constructor is fine for a Module public void bind() { bind(IFoo.class).to(Foo.class); }}public class MyModule2 extends AbstractModule { //if your module requires a context, add a constructor that will be passed a context. private Context context; //with RoboGuice 3.0, the constructor for AbstractModule will use an `Application`, not a `Context` public MyModule( Context context ) { this.context = context; } public void bind() { bind(IFoo.class).toInstance( new Foo(context)); }}
[7] use of the injection framework roboguice: (your first custom binding)