如何在具有多个ViewModel的片段之间共享数据?
class AViewModel : ViewModel() {
}
class FragmentA : Fragment() {
private lateinit var itemSelector: Selector
private lateinit var model: AViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
model = activity?.run {
ViewModelProviders.of(this)[AViewModel::class.java]
} ?: throw Exception("Invalid Activity")
itemSelector.setOnClickListener { item ->
// Update the UI
}
}
}
class BViewModel : ViewModel() {
}
class FragmentB : Fragment() {
private lateinit var model: BViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
model = activity?.run {
ViewModelProviders.of(this)[BViewModel::class.java]
} ?: throw Exception("Invalid Activity")
}
}