【问题标题】:SharedViewModel instance does not recover data from original instanceSharedViewModel 实例不会从原始实例中恢复数据
【发布时间】:2020-03-21 17:11:45
【问题描述】:

我有一个片段,我在 sharedViewModel 中更新了一个总整数,这是 shopFragment

class ShopFragment : Fragment(), AppBarLayout.OnOffsetChangedListener {

    private val model: SharedViewModel by viewModels()

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        model.updateTotal(200)
    }
}

现在,我需要在其间共享此数据的另一个片段是 BottomSheetDialogFragment ,在此片段中,我通过这样做获得了 sharedViewModel 的实例

class CartBottomSheet: BottomSheetDialogFragment() {

    private val model: SharedViewModel by viewModels ({requireParentFragment()})

 override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
          model.getTotal().observe(viewLifecycleOwner, Observer { total ->
            sheet_total_price.text = "$$total.00"
        })
    }

现在,当我尝试获取我在另一个 Fragment 中发布的 200 时,它显示为 0,这意味着该 sharedViewModel 的实例是一个新实例,因为它返回 0,因为我的 viewmodel 实例初始化了一个公共共享总数与 0

class SharedViewModel: ViewModel() {
    private val totalData = MutableLiveData<Int>()
    private var sharedTotal = 0

 fun updateTotal(total:Int){
        sharedTotal = total
        totalData.value = sharedTotal
    }

    fun getTotal():LiveData<Int>{
        return totalData
    }

现在,我的问题是,我是否需要将 BottomDialogFragment 的这个实例作为一个包传递给 sharedViewmodel 以使用,或者有什么方法可以获取相同的实例来获取总计的值

谢谢

【问题讨论】:

  • 由于 Shops 不是 Cart 片段的父级,我认为 requireParent 是问题所在,我不知道是否有比将其作为包传递给此对话框片段更简洁的方法来获取视图模型跨度>

标签: android mvvm android-architecture-components android-navigation android-architecture-navigation


【解决方案1】:

对于CartBottomSheet 片段,您可以将ShopFragment 设置为targetFragment。这样,当您创建共享 VM 时,您将获得相同的实例。基本上,如果你把它放在一起,你可以通过下面的代码来实现它:-

class CartBottomSheet: BottomSheetDialogFragment() {
    private val model: SharedViewModel?=null

    companion object {
        fun show(fragmentManager: FragmentManager, parentFragment: Fragment) {
            val sheet = CartBottomSheet()
            sheet.setTargetFragment(parentFragment, 13)
            sheet.show(fragmentManager, sheet.tag)
        }
    }
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        targetFragment?.let {
            // Create model here with it 
        }
    }

}

所以现在打开工作表你应该调用

CartBottomSheet.show(fragmentManager!!, this)

【讨论】:

  • 我正在使用导航组件来打开带有 val bundle = Bundle() bundle.putSerializable("cart",ArrayList(cartItemList)) findNavController().navigate(R.id.bottomSheet,捆绑)
  • 什么是 SelectBranchBottomSheet
  • 我认为是 CartBottomSheet.show(fragmentManager!!,this)
  • 模型应该像我现在创建的那样创建?那么现在,cartbottomSheet 是 ShopFragment 的子对象吗?
  • 看看This thread,因为您使用的是导航控制器..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多