0

I want to inject ViewBinding using Hilt.

@AndroidEntryPoint
class AlbumListFragment : Fragment(R.layout.album_list_fragment) {

   @Inject 
   lateinit var binding: AlbumListFragmentBinding
....

and configured @Provides for binding:

@Module
@InstallIn(ActivityComponent::class)
internal object MainModule {

   @Provides
   fun provideAlbumListFragmentBinding(albumListFragment: AlbumListFragment): AlbumListFragmentBinding {
        return AlbumListFragmentBinding
            .inflate(albumListFragment.layoutInflater)
    }
}

But I get an error: cannot be provided without an @Inject constructor or an @Provides-annotated method. This type supports members injection but cannot be implicitly provided.

I tried to add @Inject constructor to the fragment

@AndroidEntryPoint
class AlbumListFragment @Inject constructor() : Fragment(R.layout.album_list_fragment) {}

But then it creates a circular dependency: error: [Dagger/DependencyCycle] Found a dependency cycle:

There is a way to use Hilt to inject binding in order to avoid the following boilerplate code in each fragment?

override fun onCreateView(
   inflater: LayoutInflater,
   container: ViewGroup?,
   savedInstanceState: Bundle?
): View {
   binding = AlbumListFragmentBinding.inflate(inflater, container, false)
   return binding.root
}
Yanay Hollander
  • 327
  • 1
  • 5
  • 19

1 Answers1

2

I don't think you can achieve this via DI, since you cannot get instance of LayoutInflater, without appropriate context. What you can do to reduce boilerplate code is to create BaseFragment class and handle view binding inflation in base class for all your fragments. Something like this: How using ViewBinding with an abstract base class, but you can adapt it for your needs. GL

Samir Spahic
  • 542
  • 2
  • 10