我有一个ViewModel,我在Fragment和DialogFragment中使用过。在对话片段中,我尝试更新对话片段中的 MutableLiveData 值,然后在我的片段中使用该值。当我检查对话框片段时,我在 MutableLiveData 中有数据,但是当尝试访问片段中的数据时,我得到了空。可以指导我如何解决此问题吗?
在视图中模型:
val width = MutableLiveData<String>()
val height = MutableLiveData<String>()
val length = MutableLiveData<String>()
在对话片段中:
vModel.width.value = "6"
vModel.height.value = "6"
vModel.length.value = "6"
在我的片段中,当我尝试从 MutableLiveData 访问数据时:
println(vModel.width.value)
println(vModel.height.value)
println(vModel.length.value)
这是我的基本片段:
abstract class BaseFragment<B : ViewDataBinding, V : BaseViewModel>(
private val layout: Int,
private val viewModel: V
) : Fragment() {
private lateinit var v: View
protected lateinit var binding: B
protected lateinit var vModel: V
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
super.onCreateView(inflater, container, savedInstanceState)
binding = DataBindingUtil.inflate(inflater, layout, container, false)
binding.lifecycleOwner = viewLifecycleOwner
this.vModel = viewModel
initVariables()
initObserves()
initViews()
return binding.root
}
abstract fun initVariables()
abstract fun initObserves()
abstract fun initViews()
}
这是我的BaseDialogFragment:
abstract class BaseDialogFragment<B : ViewDataBinding, V : BaseViewModel>(
private val layout: Int,
private val viewModel: V
) : DialogFragment() {
private lateinit var v: View
protected lateinit var binding: B
protected lateinit var vModel: V
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
super.onCreateView(inflater, container, savedInstanceState)
binding = DataBindingUtil.inflate(inflater, layout, container, false)
binding.lifecycleOwner = viewLifecycleOwner
this.vModel = viewModel
initVariables()
initObserves()
initViews()
return binding.root
}
abstract fun initVariables()
abstract fun initObserves()
abstract fun initViews()
}
确保使用活动上下文加载 ViewModel,以便一个实例将与所有片段共享,而不是为每个片段重新创建
像这样的东西
val viewModel by activityViewModels<MainViewModel> ()