我在HomeFragment中创建了一个选项卡布局(WorkoutAtHome和Workoutinstudio),显然我已经使用了片段来创建选项卡布局。现在我想注入ViewModelProviderFactory对象内的tablayout片段。因此,我所做的是添加home片段与@ContributesAndroidInjector和两个tablayout片段都在homeFragment模块内。代码如下:
ActivityBuilderModule
@Module
abstract class ActivityBuilderModule {
@ContributesAndroidInjector(
modules = [
FragmentBuilderModule::class
]
)
abstract fun contributeMainActivity(): MainActivity
}
FragmentBuilderModule
@Module
interface FragmentBuilderModule {
@ContributesAndroidInjector
fun contributeSplashFragment(): SplashFragment
@HomeScope
@ContributesAndroidInjector(
modules = [
TabBuilderModule::class,
HomeViewModelModule::class,
HomeModule::class]
)
fun contributeHomeFragment(): HomeFragment
@LocationScope
@ContributesAndroidInjector(
modules = [
LocationModule::class
]
)
fun contributeLocationFragment(): LocationFragment
}
TabBuilderModule
@Module
interface TabBuilderModule {
@ContributesAndroidInjector
fun contributeWorkoutInStudio(): WorkoutInStudioFragment
@ContributesAndroidInjector
fun contributeWorkoutAtHomeFragment(): WorkoutAtHomeFragment
}
现在的问题是,每当我想注入任何tablayout片段然后我得到错误说,No injector factory bound for Class<com.example.fitternitytest.view.fragment.home.tabs.WorkoutInStudioFragment>
WorkoutAtHomeFragment
class WorkoutAtHomeFragment :DaggerFragment() , HasSupportFragmentInjector {
private var count = 0
@Inject
lateinit var factory: ViewModelProviderFactory
private val viewModel: HomeViewModel by activityViewModels { factory }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
}
同样的代码也适用于其他片段。
FirstHasFragmentInjector由DaggerFragment实现-你为什么又这么做了?
class WorkoutAtHomeFragment :DaggerFragment() , HasSupportFragmentInjector {
第二-您缺少用于WorkoutIn的注入器工厂studioffragment,看到的错误,但你已经显示的代码锻炼在HomeFragment
第三,这不再是使用Dagger的方式了。你应该使用Hilt这意味着你不再需要像@ContributesAndroidInjector这样的东西了
你只说:
@AndroidEntryPoint
class WorkoutAtHomeFragment : Fragment() {
...
}
柄教程: https://developer.android.com/training/dependency-injection/hilt-android
在页面末尾有更多教程和代码库。