如何将HiltViewModel注入到Java类中

huangapple go评论68阅读模式
英文:

How to inject HiltViewModel into Java class

问题

你可以使用以下代码将 ViewModel 注入到 Java 类中:

private MyViewModel viewModel = new ViewModelProvider(this).get(MyViewModel.class);
英文:

I'm using such code to inject viewmodel into kotlin class

val viewModel  = viewModel<UserViewModel>()
or
private val viewModel: MyViewModel by viewModels()

but how to inject viewModel into Java class?

答案1

得分: 1

// 第1步:创建一个ViewModelProvider
ViewModelProvider.AndroidViewModelFactory factory = ViewModelProvider.AndroidViewModelFactory.getInstance(getApplication());

// 第2步:检索ViewModel实例
viewModel = new ViewModelProvider(this, factory).get(MyViewModel.class);

// 现在你可以在你的Java类中使用viewModel实例
// ...

英文:
      // Step 1: Create a ViewModelProvider
    ViewModelProvider.AndroidViewModelFactory factory = ViewModelProvider.AndroidViewModelFactory.getInstance(getApplication());

    // Step 2: Retrieve the ViewModel instance
    viewModel = new ViewModelProvider(this, factory).get(MyViewModel.class);

    // Now you can use the viewModel instance in your Java class
    // ...

huangapple
  • 本文由 发表于 2023年7月13日 15:43:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76677009.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定