Anoop Krishnan
Anoop Krishnan

Reputation: 331

Dagger 2 injecting object

I have made an android bottom bar in activity and thought i'd use dagger2 to set listener for it. How ever I am confused as to how to get the getSupportFragmentManager() inside the listener class. Here's what i'm trying

public class MainActivity extends AppCompatActivity {

@BindView(R.id.bottomNavigationView)
BottomNavigationView bottomNavigationView;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);
    BottomBarComponent bottomBarComponent = DaggerBottomBarComponent.builder()
            .bottomBarModule(new BottomBarModule(getSupportFragmentManager()))
            .build();

}
}

The component part is

@Singleton
@Component(modules = {BottomBarModule.class})
public interface BottomBarComponent {
 void inject(BottomNavigationListener listener);
}

The module is

@Module
public class BottomBarModule {
private FragmentManager manager;

public BottomBarModule(FragmentManager context) {
    this.manager = context;
}

@Singleton
@Provides
public FragmentManager provideSupportManager(){
    return manager;
}
}

And need to get fragmentsupportManager here

public class BottomNavigationListener implements BottomNavigationView.OnNavigationItemSelectedListener{


@Inject
FragmentManager manager;

public void BottomNavigationListener() {

   //somehow need to get fragmentSupportManager here
}

@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {

    return true;
}
}

How do I do this?

Upvotes: 0

Views: 724

Answers (1)

Nikolay
Nikolay

Reputation: 1448

You need to share instance of BottomBarComponent with your BottomNavigationListener and invoke inject() method on it.

BottomNavigationListener.class

...
public void BottomNavigationListener(BottomBarComponent injector) {
   //somehow need to get fragmentSupportManager here
   injector.inject(this); // now manager field must be filled
}
...

MainActivity.class

...
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);
    BottomBarComponent bottomBarComponent = DaggerBottomBarComponent.builder()
            .bottomBarModule(new BottomBarModule(getSupportFragmentManager()))
            .build();
    // pass BottomBarComponent to BottomNavigationListener for injecting FragmentManager
    BottomNavigationListener listener = new BottomNavigationListener(bottomBarComponent);
}
...

But very strange thing you're trying to do. It's all equivalent to passing FragmentManager directly to BottomNavigationListener without using Dagger.

Upvotes: 0

Related Questions