当前,要在 Activity 中获取例如毕加索的实例,我需要向AppComponent添加注入(inject)方法。如何避免添加inject方法,因为我在应将其注入(inject)的地方有很多 fragment 和 View :

AppComponent.class:

@ForApplication
@Singleton
@Component(
        modules = {AppModule.class,OkHttpClientModule.class,NetworkApiModule.class,NetworkAuthModule.class})
public interface AppComponent {
    void inject(Fragment1 obj);
    void inject(Fragment2 obj);
    void inject(Fragment3 obj);
    void inject(Fragment4 obj);
    void inject(Fragment5 obj);
    void inject(Fragment6 obj);
    ...
    }

Fragment1.class
public class Fragment1 extends Fragment {
    @Inject Picasso mPicasso;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyApplication.getComponent(getContext()).inject(this);
    }
}

我的类(class) :

AppModule.class:
@Module
public class AppModule {
    private MyApplication mApplication;

    public AppModule(@NonNull MyApplication mApplication) {
        this.mApplication = mApplication;
    }

    @Provides
    @NonNull
    @Singleton
    public Application provideApplication() {
        return mApplication;
    }


   @Provides
   @ForApplication
    Context provideContext(){
        return mApplication;
    }

    @Provides
    @Singleton
    Picasso providesPicasso(@ForApplication Context context) {
        return new Picasso.Builder(context).build();
    }
}

ForApplication.class:
@Scope
@Retention(RUNTIME)
public @interface ForApplication {
}

MyApplication.class
public class MyApplicationextends Application {
    static Context mContext;
    private AppComponent component;
    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;

        setupComponent();
    }

    private void setupComponent() {
        component = DaggerAppComponent.builder().appModule(new AppModule(this)).build();
        component.inject(this);
    }

    public AppComponent getComponent() {
        if (component==null)
            setupComponent();
        return component;
    }



public static AppComponent getComponent(Context context) {
        return ((MyApplication) context.getApplicationContext()).getComponent();
    }

更新

我还希望为 fragment 插入适配器,如果我将Inject添加到BaseFragment,则BaseFragment将具有所有子 fragment 的所有适配器

最佳答案

一种解决方案是将继承用于注入(inject)。

只需使用@Inject Picasso实例定义一个BaseFragment,在DaggerComponent中为此BaseFragment创建一个注入(inject)方法,并在BaseFragment的onCreate方法中调用它。更具体的Fragment(例如Fragment1、2 ..)可以从此BaseFragment继承并使用Picasso实例。

10-07 19:08
查看更多