roboguice how to inject custom class

后端 未结 1 370
梦如初夏
梦如初夏 2021-01-03 04:56

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

相关标签:
1条回答
  • 2021-01-03 05:09

    Injection of a custom class in RoboActivity

    You can inject a custom class simply using the @Inject annotation, but the injected class must satisfy one of the following conditions:

    • The custom class have a default constructor (with no argument)
    • The custom class have one injected constructor.
    • The custom class has a Provider which handle the instantiation (more complex)

    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

    Injection inside a custom class

    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.

    0 讨论(0)
提交回复
热议问题