k_wisniewski
k_wisniewski

Reputation: 2519

Inject adapter into activity

I'm learning how to use RoboGuice (and Dependency Injection in general). The problem I have is I want to inject custom FragmentPagerAdapter into activity, but I need to pass FragmentManager somehow. Is there a way to do that? In documentation they present a way to pass context, but I need to pass FragmentManager - do I need to do that the same way?

Upvotes: 1

Views: 736

Answers (2)

jimmyorr
jimmyorr

Reputation: 11698

For Dagger:

Define a binding for the FragmentManager in an Activity-specific subgraph using Activity.getFragmentManager(). Then inject the FragmentManager into the FragmentPagerAdapter, and inject the FragmentPagerAdapter into the Activity.

public class ActivityModule {

  private final Activity activity;

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

  @Provides
  public Activity getActivity() {
    return activity;
  }

  @Provides
  FragmentManager provideFragmentManager(Activity activity) {
    return activity.getFragmentManager();
  }
}

Upvotes: 1

Tavian Barnes
Tavian Barnes

Reputation: 12922

It looks like you can inject the Activity directly. Then you should be able to just call activity.getFragmentManager(). Or if you're using the support library, ((FragmentActivity) activity).getSupportFragmentManager().

Upvotes: 0

Related Questions