Android手柄-两个fragment之间共享的ViewModel



我在我的项目中使用Jetpack导航和手柄,我想在两个片段之间共享ViewModel,像这样:

  • Fragment A: use ViewModel A
  • 在片段A导航到片段B:使用ViewModel B
  • 在片段B中导航到片段C:使用ViewModel B的实例
  • 如果从C返回到B,返回到A,则ViewModel B将被销毁。

如何配置ViewModel B这样?

更新:我找到了一种使用柄自定义作用域的方法,但我不知道如何实现它。

提前感谢。

您可以使用activityViewModels()与ViewModel遵循宿主活动的生命周期。

class BFragment: Fragment() {
// Using the activityViewModels() Kotlin property delegate from the
// fragment-ktx artifact to retrieve the ViewModel in the activity scope
private val viewModel: BViewModel by activityViewModels()
}
class CFragment : Fragment() {
private val viewModel: CViewModel by viewModels()

private val shareViewModel: BViewModel by activityViewModels()
}

或者如果片段C是B的子片段,你可以自定义视图模型的生命周期如下:

class BFragment: Fragment() {
// Using the viewModels() Kotlin property delegate from the fragment-ktx
// artifact to retrieve the ViewModel
private val viewModel: BViewModel by viewModels()
}
class CFragment: Fragment() {
// Using the viewModels() Kotlin property delegate from the fragment-ktx
// artifact to retrieve the ViewModel using the parent fragment's scope
private val shareViewModel: BViewModel by viewModels({requireParentFragment()})
private val viewModel: CViewModel by viewModels()
}

更多信息:与fragments通信

您可以使用navGraphViewModels。用Fragment B创建一个嵌套图;C,两者将共享相同的navGraphViewModel

<navigation android:id="@+id/nav_graph_a"
app:startDestination="@id/dest_a">
<fragment android:id="@+id/dest_a"/>
<navigation android:id="@+id/nav_graph_b_c"                  
app:startDestination="@id/dest_b">
<fragment android:id="@+id/dest_b"/>
<fragment android:id="@+id/dest_c"/>
</navigation>               

</navigation>

https://developer.android.com/guide/navigation/navigation-programmatic

https://medium.com/sprinthub/a-step-by-step-guide-on-how-to-use-nav-graph-scoped-viewmodels-cf82de4545ed

最新更新