Reputation: 2483
I am reading documentation about Dagger2. The thing is I have clear how inject a class how has Context
using this
But my doubt is with the following class for example:
public class SocialControler{
private ImageView twitterLogo;
private ImageView googleLogo;
public SocialControler(ImageView twitter, ImageView google){
twitterLogo = twitter;
googleLogo = google;
}
//Getters and Setters
}
So in my MainActivity
I will have something like this
SocialControler mSocial = new SocialControler(mTwitterLogo, mGoogleLogo);
Should I inject this class using @Inject
anotation instead doing new
, so no more new
on our Activity? If yes How?
I am stuck in the @Mudule
. How I can provide a View inside de Module
?
@Module
public class AppModuleSocialMediaManager {
@Provides
public MainActivity provideActivity(){
return new MainActivity();
}
@Provides
public SocialMediaClickManager provideMediaManager(MainActivity mainActivity, View twitterLogo, View googleLogo) {
return new SocialMediaClickManager(mainActivity);
}
@Provides
public View provideTwitter(){
return ?
//from here how I can provide a View
}
}
Upvotes: 2
Views: 273
Reputation: 1458
I would not recommend the architecture you're using to build your app, i.e. make your controllers depend on exact views, but if you're fine with that then you can implement your module like this:
@Module
public class AppModuleSocialMediaManager {
private final MainActivity mainActivity;
public AppModuleSocialMediaManager(MainActivity mainActivity) {
this.mainActivity = mainActivity;
}
@Provides
@Named("twitter_view")
View provideTwitterView() {
return mainActivity.findViewById(..);
}
@Provides
@Named("google_view")
View provideGoogleView() {
return mainActivity.findViewById(..);
}
@Provides
SocialController provideSocialController(@Named("twitter_view") View twitterView, @Named("google_view") View googleView) {
return new SocialController(twitterView, googleView);
}
}
Then you need to declare another component. Let's say it's MainActivityComponent
:
@Component(modules = AppModuleSocialMediaManager.class)
public interface MainActivityComponent {
void inject(MainActivity activity);
}
After that in your activity you can do something like this:
public class MainActivity extends Activity {
@Inject
SocialController socialController;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DaggerMainActivityComponent.Builder()
.appModuleSocialMediaManager(new AppModuleSocialMediaManager(this))
.build()
.inject(this);
socialController.doSomething();
}
}
Upvotes: 1