Android Hilt - 两个Fragment之间共享ViewModel

3

我在我的项目中使用Jetpack Navigation和Hilt,希望只在两个Fragment之间共享ViewModel:

  • Fragment A:使用ViewModel A
  • 从Fragment A导航到Fragment B:使用ViewModel B
  • 从Fragment B导航到Fragment C:使用ViewModel B的实例
  • 如果从C返回B,再返回A,则将销毁ViewModel B。

如何配置ViewModel B?

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

谢谢提前。

2个回答

8
您可以使用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的子片段,则可以按以下方式自定义ViewModel的生命周期:

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()
}

更多信息:与片段通信

我认为这不太合适。当我从 Fragment A 导航到 B 时,我希望 ViewModel B 有一个新实例。按照您的方式,当 Fragment B 进入 onDestroy() 时,ViewModel B 并没有被清除。 - PhongBM
你有没有找到不使用导航图的解决方案? - Aldrin Joe Mathew

3

您可以使用navGraphViewModels。创建一个嵌套图与片段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


我也找到了这份文档,但有没有不使用导航的方法呢?谢谢。 - PhongBM

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接