Dagger2注入了一切?

时间:2016-12-22 12:53:47

标签: android dagger-2

我正在阅读有关Dagger2的文档。问题是我已经明确了如何使用Context

this注入课程

但我怀疑是以下课程为例:

public class SocialControler{

private ImageView twitterLogo;
private ImageView googleLogo;

public SocialControler(ImageView twitter, ImageView google){
twitterLogo = twitter;
googleLogo = google;
}
//Getters and Setters

}

所以在我的MainActivity我会有类似的东西

SocialControler mSocial = new SocialControler(mTwitterLogo, mGoogleLogo);

我应该使用@Inject anotation注入此类而不是new,所以我们的Activity上不再有new吗?如果是的如何?

我被困在@Mudule。我如何在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
    }
}

1 个答案:

答案 0 :(得分:1)

我不推荐您用来构建应用程序的架构,即让您的控制器依赖于确切的视图,但如果您对此感到满意,那么您可以像这样实现您的模块:

 @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);
     }

 }

然后你需要声明另一个组件。让我们说出MainActivityComponent

 @Component(modules = AppModuleSocialMediaManager.class)
 public interface MainActivityComponent {
     void inject(MainActivity activity);
 }

在您的活动之后,您可以执行以下操作:

 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();
     }

 }