如何使用多个ViewModel在片段之间共享数据

时间:2019-10-01 14:50:29

标签: android kotlin

如何在具有多个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")
    }
}

0 个答案:

没有答案