如何使用Dagger Hilt为依赖Listener接口的List Adapter类提供依赖注入?
Alright, let's tackle how to provide the Listener interface dependency using Dagger Hilt in your setup. Here's a step-by-step breakdown that fits your code structure:
1. Create a Hilt Module to Bind the Interface to Its Implementation
Since your MainActivity implements the Listener interface, we need to tell Hilt to use the MainActivity instance whenever a Listener is requested. We'll do this with a Hilt module:
@Module @InstallIn(ActivityComponent::class) abstract class ListenerModule { @Binds @ActivityScoped abstract fun bindListener(mainActivity: MainActivity): Listener }
Let's break down what this does:
@Module: Marks this class as a Hilt module that provides dependencies.@InstallIn(ActivityComponent::class): Installs the module in the Activity component, meaning the dependency is scoped to the Activity's lifecycle.@Binds: Tells Hilt to use theMainActivityinstance (which implementsListener) whenever aListenertype is requested. This is more efficient than@Providesfor interface-to-implementation bindings.@ActivityScoped: Ensures the sameListenerinstance (yourMainActivity) is used throughout the Activity's lifecycle.
2. Inject the PhoneAdapter in Your MainActivity
Since your PhoneAdapter has an @Inject constructor, Hilt can automatically create its instance and pass in the Listener (your MainActivity). Just inject the adapter in your MainActivity:
@AndroidEntryPoint class MainActivity : AppCompatActivity(), Listener { private val binding by lazy { ActivityMainBinding.inflate(layoutInflater) } // Inject the PhoneAdapter using Hilt @Inject lateinit var phoneAdapter: PhoneAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) // Assign the adapter to your RecyclerView binding.recyclerView.adapter = phoneAdapter } // Implement the Listener interface methods override fun deleteOnClick(position: Int, userId: Int) { // Add your delete logic here } override fun updateOnClick(position: Int, userId: Int, name: String, phoneNo: Long) { // Add your update logic here } }
3. Verify Your Core Hilt Setup
Don't forget the foundational Hilt setup that makes this work:
- Ensure your app's Application class is annotated with
@HiltAndroidApp:
@HiltAndroidApp class MyApp : Application()
- Double-check that your
PhoneAdapter's constructor is correctly annotated with@Inject(which you already have in your code).
That's it! Hilt will now handle providing the Listener dependency to your PhoneAdapter by using the MainActivity instance, since it implements the interface.
内容的提问来源于stack exchange,提问作者Jayant Kumar

