I have created a tab layout(WorkoutAtHome and Workoutinstudio) inside the HomeFragment and to create tab layout obviously i have used fragment. Now i want to inject ViewModelProviderFactory object inside the tablayout fragments. so for that what I have done is added the home fragment with the @ContributesAndroidInjector and both tablayout fragments are inside homeFragment module. Below is the code.
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
}
Now the issue is whenever i want to inject anything the tablayout fragment then i get error saying that 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)
}
}
Same code is for other fragment also.
First HasFragmentInjector is implemented by DaggerFragment - why are you doing it again?
class WorkoutAtHomeFragment :DaggerFragment() , HasSupportFragmentInjector {
Second - you are missing injector factory for WorkoutInStudioFragment, seen by the error, but you have shown the code for WorkoutAtHomeFragment
Third - this is not the way to use Dagger anymore. You should be using Hilt which will mean that you no more need things like @ContributesAndroidInjector
You only say:
@AndroidEntryPoint
class WorkoutAtHomeFragment : Fragment() {
...
}
Hilt Tutorial: https://developer.android.com/training/dependency-injection/hilt-android
There are more tutorials and a codelab in the end of the page.