简体   繁体   English

Android Jetpack Compose 从 Composable 内的 Fragment 获取活动视图模型

[英]Android Jetpack Compose get Activity View Model from Fragment inside Composable

I'm having an issue getting the activity view model from a fragment in a composable我在从可组合的片段中获取活动视图模型时遇到问题

private val birthdayViewModel: BirthdayViewModel by activityViewModels()

When I use viewModels() there is no issue当我使用 viewModels() 时没有问题

private val birthdayViewModel: BirthdayViewModel by viewModels()

Fetching the view model in composable like以可组合的方式获取视图模型

val birthdayViewModel: BirthdayViewModel = viewModel()
val formItem by birthdayViewModel.birthdayFormItem.observeAsState()

The issue is that the form item errors to null when using activityViewModels but not when using viewModels问题是使用 activityViewModels 时表单项错误为 null 而使用 viewModels 时则不然

When I run in debug mode to check the value of the formItem I get this error message: "Cannot find local variable 'formItem' with type com.form.FormSpec$FormItem"当我在调试模式下运行以检查 formItem 的值时,我收到此错误消息:“找不到类型为 com.form.FormSpec$FormItem 的局部变量‘formItem’”

Could this be a gradle versioning issue?这可能是 gradle 版本控制问题吗?

Please help :)请帮忙 :)

If you're not using Hilt, assuming that you have instantiated your view model like this in your activity:如果您没有使用 Hilt,假设您已经在您的活动中像这样实例化了您的视图模型:

val viewModel: YourViewModel by viewModels()

you can get the same instance using this:你可以使用这个获得相同的实例:

val viewModel = viewModel(
    modelClass = YourViewModel::class.java,
    viewModelStoreOwner = LocalContext.current as YourActivity
)
private val activityViewModel: ActivityViewModel by activityViewModels()
private val fragmentViewModel: FragmentViewModel by viewModels()

Composable(fragmentViewModel, activityViewModel)

The problem had to do with scopes.问题与范围有关。 I was not passing the view models into my composable directly, but rather, was doing this in the composable constructor which didn't lead to both of my viewModels having a fragment scope.我没有将视图模型直接传递到我的可组合中,而是在可组合构造函数中执行此操作,这不会导致我的两个视图模型都具有片段范围。

Composable(
   fragmentViewModel: FragmentViewModel = viewModel(), 
   activityViewModel: ActivityViewModel = viewModel()
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM