使用Hilt如何在无构造参数与ViewModelFactory时注入类到ViewModel?是否可行?
Absolutely! You can absolutely inject dependencies into ViewModels using Hilt without writing custom ViewModelFactory classes or manually passing constructor parameters—though the setup is slightly different from how you inject into Fragments or Activities. Here's how it works:
Step 1: Ensure Hilt is properly set up in your project
First, make sure you've got the basic Hilt configuration done:
- Add the Hilt Gradle plugins and dependencies to your project (app-level and project-level build files)
- Annotate your application class with
@HiltAndroidAppto initialize Hilt's dependency graph
Step 2: Annotate your ViewModel with @HiltViewModel
This is the key difference from injecting into Fragments. For ViewModels, you need the @HiltViewModel annotation (instead of just @Inject) to tell Hilt to generate a specialized factory that handles injecting dependencies into your ViewModel.
Then, use @Inject on your ViewModel's constructor to declare the dependencies you want injected:
// Example dependency to inject class UserRepository @Inject constructor() { // Your repository logic here fun fetchUserInfo() { // Implementation } } // ViewModel with injected dependency @HiltViewModel class MyViewModel @Inject constructor( private val userRepository: UserRepository ) : ViewModel() { // Use the injected repository in your ViewModel logic fun loadUser() { userRepository.fetchUserInfo() } }
Step 3: Access the ViewModel in your Fragment/Activity
Just like with Fragments, your host Fragment or Activity needs to be annotated with @AndroidEntryPoint. Then, you can retrieve the ViewModel using the standard by viewModels() delegate—no custom factory required:
@AndroidEntryPoint class MyFragment : Fragment() { // Automatically gets the ViewModel with injected dependencies private val viewModel: MyViewModel by viewModels() override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // Use the viewModel as normal viewModel.loadUser() } }
How this works under the hood
When you use @HiltViewModel, Hilt generates a HiltViewModelFactory that's responsible for creating your ViewModel instance and injecting its constructor dependencies. The @AndroidEntryPoint annotation on your Fragment/Activity ensures that the ViewModelProvider uses this generated factory automatically, so you never have to pass it explicitly.
Important Notes
- All dependencies in your ViewModel's constructor must be accessible to Hilt (either via
@Injecton their own constructor, or bound in a Hilt module) - You can't use
@Injectdirectly on a ViewModel without@HiltViewModel—Hilt needs this annotation to handle the ViewModel's lifecycle correctly - This works for both Activities and Fragments as long as they're annotated with
@AndroidEntryPoint
内容的提问来源于stack exchange,提问作者Pavel Poley

