Jetpack Navigation和viewModel實現(xiàn)fragment的切換和數(shù)據(jù)共享

Navigation的使用請看筆者的另一筆記

http://www.itdecent.cn/p/bb31d2686add

本案例來自于:

https://b23.tv/BV1w4411t7UQ/p19

一、介紹

個人理解:ViewModel的生命周期與Activity生命周期一致,故可以通過在fragment中獲取viewModel來實現(xiàn)fragment之間的數(shù)據(jù)共享,如有錯誤歡迎指正

原理圖

二、關(guān)鍵代碼---fragment 中獲取viewModel

//fragment 中獲取viewModel 
override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        //viewmodel的持有者為Acitvity
        mViewModel=ViewModelProvider(activity!!).get(MyViewModel::class.java)
        var binding:FragmentDetailBinding=DataBindingUtil.inflate(inflater,R.layout.fragment_detail,container,false)
        binding.data=mViewModel
        //databing的生命周期也是與Activity一致
        binding.lifecycleOwner=activity
        return binding.root
    }

案例地址

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容