我试图使用ViewModel将数据从DialogFragment发送到Fragment,但Fragment和Dialog Fragment似乎都引用了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)
}
}
第页。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: Bundle?) {
super.onViewCreated(view, savedInstanceState)
...
}
}
请在这里阅读android文档中的更多内容:https://developer.android.com/topic/libraries/architecture/viewmodel#sharing