如何解决如何使用ViewModel将数据从DialogFragment发送到Fragment
我正在尝试使用ViewModel将数据从DialogFragment发送到Fragment,但似乎fragment和Dialog片段都引用了ViewModel的不同实例。所以我无法访问数据。有什么办法可以解决这个问题?谢谢
这是我的片段
@AndroidEntryPoint
class FragmentToReceiveData:BaseFragment(R.layout.fragment_1){
private val viewModel: AddScheduleViewModel by viewModels()
override fun onViewCreated(view: View,savedInstanceState: Bundle?) {
Log.d(TAG,"onViewCreated: $viewModel") // will print ...MyViewModel@62274cc
viewModel.dataFromDialog.observe(viewLifecycleOwner){
//nothing happens
}
}
.
.
.
private fun openDialog(){
val action=FragmentToReceiveDataDirections.actionFragmentToReceiveDataToExampleDialog()
findNavController().navigate(action)
//exampleDialog.show(requireActivity().supportFragmentManager,"alarmDialog") //same issue
}
}
这是ViewModel:
class MyViewModel @ViewModelInject constructor(){
var dataFromDialog=MutableLiveData<SomeClass>()
fun saveDataFromDialog(data:SomeClass){
dataFromDialog.value=data
}
}
这是我的DialogFragment
@AndroidEntryPoint
class ExampleDialog:DialogFragment() {
val viewModel:MyViewModel by viewModels()
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
Log.d(TAG,"onCreateDialog: $viewModel") // will print ...MyViewModel@125436
.
.
.
viewMode.saveDataFromDialog(data)
}
}
P.S:我正在使用单一活动架构,所以我不确定activityViewModels()是否是个好主意
解决方法
为了在片段之间共享ViewModel,可以使用activityViewModels()
。例如,
class SharedViewModel : ViewModel() {
...
}
class MasterFragment : Fragment() {
// Use the 'by activityViewModels()' Kotlin property delegate
// from the fragment-ktx artifact
private val model: SharedViewModel by activityViewModels()
override fun onViewCreated(view: View,savedInstanceState: Bundle?) {
super.onViewCreated(view,savedInstanceState)
...
}
}
class DetailFragment : Fragment() {
// Use the 'by activityViewModels()' Kotlin property delegate
// from the fragment-ktx artifact
private val model: SharedViewModel by activityViewModels()
override fun onViewCreated(view: View,savedInstanceState)
...
}
}
请在此处的android文档中详细了解:https://developer.android.com/topic/libraries/architecture/viewmodel#sharing
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。