Nic*_*hek 7 java android dependency-injection dagger-2
目前,要在活动中获取Picasso的实例,我需要向AppComponent添加注入方法.如何避免添加inject方法,因为我有很多片段和视图应该注入:
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);
...
}
Run Code Online (Sandbox Code Playgroud)
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);
}
}
Run Code Online (Sandbox Code Playgroud)
我的课程 :
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();
}
}
Run Code Online (Sandbox Code Playgroud)
ForApplication.class:
@Scope
@Retention(RUNTIME)
public @interface ForApplication {
}
Run Code Online (Sandbox Code Playgroud)
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();
}
Run Code Online (Sandbox Code Playgroud)
UPDATE
我还想为片段注入适配器,如果我要向BaseFragment添加注入,那么BaseFragment将为所有子片段提供所有适配器
我通过使用lombok 库添加委托类解决了这个问题
@Accessors(prefix = "m")
public class AdapterDelegate {
@Getter @Inject Lazy<FlatAdapter> mFlatAdapterLazy;
public AdapterDelegate(){
MyApplication.getComponent(MyApplication.getContext()).inject(this);
}
public static AdapterDelegate get() {
return new AdapterDelegate();
}
}
Run Code Online (Sandbox Code Playgroud)
并且在一个活动中
public class MainActivity extends Activity {
FlatAdapter mFlatAdapter = AdapterDelegate.get().getFlatAdapterLazy().get();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
390 次 |
最近记录: |