问题描述
我正在尝试使用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