简体   繁体   中英

How to create activity context dependent object in dagger?

I have a situation, I have injected all objects using Dagger 2, But in one situation I am unable to rectify how to inject the object.

Following is the situation

mPager.setAdapter(new MyPagerAdapter(this));

Now in the above statement, I have to inject the MyPagerAdapter object using Dagger, but it requires current activity context.

So how to forward the activity context to the Dagger module?

(turning @EpicPandaForce's comment into an answer)

You can write a module that takes an Activity in its constructor parameters like this:

@Module
@ActivityScope 
public class MyModule {
    private final Activity activity;

    public MyModule(Activity activity) {
        this.activity = activity;
    }

    @Provides
    @ActivityScope
    Activity activity() {
        return activity;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM