Search code examples
javaandroidandroid-fragmentsandroid-architecture-navigationdagger-hilt

How to use navigation component when Hilt changes the names of the fragments


I'm creating an Android app (Java) and using Navigation Components and Hilt for the first time. In the Navigation Editor I'm creating destinations and see that the fragments I created that have been annotated with @AndroidEntryPoint now show as "Hilt_" + the fragment name. Now my app cannot build because the compiler is looking for a constructor with "Hilt_" + the fragment name instead of just the fragment name. Ex: my fragment is named HomeFragment but in the Navigation Editor it is called Hilt_HomeFragment. Error I get when compiling:

Caused by: androidx.fragment.app.Fragment$InstantiationException: Unable to instantiate fragment com.blah.blah.fragment.Hilt_HomeFragment: could not find Fragment constructor

How should the name discrepancies be handled so I can use Hilt & navigation components together?


Solution

  • "Hilt_HomeFragment" is a class generated for Hilt purposes, you should not care about it. Just make the Build -> Clean Project. Then go to your graph, clear the wrong name and write the proper one with the full package path. For example:

    android:name="com.example.home.HomeFragment"
    

    When you start typing in the name field, Android Studio will show you the prompt with matching fragments you can use - just select the proper one and the name will be filled with it.