SharedViewModel实例未从原始实例恢复数据

问题描述 投票:0回答:1

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

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的此实例以供使用,或者是否有任何方法可以使同一实例获得total的值

谢谢

android mvvm android-architecture-components android-navigation android-architecture-navigation
1个回答
0
投票

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

CartBottomSheet

所以现在应该致电开张

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

    companion object {
        fun show(fragmentManager: FragmentManager, parentFragment: Fragment) {
            val sheet = SelectBranchBottomSheet()
            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 
        }
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.