使用AndroidInjector进行一般活动/片段

时间:2018-08-21 04:44:14

标签: android generics dagger-2 dagger androidinjector

有一个通用片段

public class MyFragment<TYPE> extends Fragment {

@Inject 
SomeClass class;

public MyFragment(){}

}
}

我无法将此片段添加到片段绑定模块,因为Dagger抱怨说它是原始类型。

如何在绑定模块中提及TYPE类?

我的绑定模块现在看起来像这样:

@Module
public abstract class BindingModule {

    @ContributesAndroidInjector(modules = MyFragmentModule.class)
    abstract MyFragment bindMyFragment();


} 

错误

error: [dagger.android.AndroidInjector.inject(T)] MyFragment has type parameters, cannot members inject the raw type.

1 个答案:

答案 0 :(得分:0)

首先,我不得不说片段是特殊类,它的实例化必须由OS完成,通过将其添加到模块中,您可以绕过必须由OS控制的片段的生命周期。

django-smart-selects

但是,如果您希望按模块提供它,则必须对普通类型使用限定符。如下更改模块:

 @Module
public abstract class BindingModule {

    @ContributesAndroidInjector(modules = MyFragmentModule.class)
    @Name('YourTypeName')
    abstract MyFragment<YourType> bindMyFragment();  
} 

因此,无论您在哪里注入它,都必须指定类型及其限定符:

@Inject
@Name('YourTypeName')
MyFragment<YourType> fragmentReference;
相关问题