简体   繁体   中英

Change fragment from ViewModel in MVVM architecture

I am developing an agenda app for practise MVVM architecture and SQLite databases but i need to change fragment from inside of fragment. So for calendarFragment i created this viewModel but i can't use .supportFragmentManager method without MainActivity context. How can i solve this problem ?


class calendarFragmentViewModel(application: Application) : AndroidViewModel(application) {

    fun fragmentChanger(fragment : Fragment, context: Context?) {
        var transaction = (context as MainActivity).supportFragmentManager.beginTransaction()
            transaction.replace(com.cagataysencan.agendea.R.id.frameLayout,fragment)
            transaction.commit()
        }
    }

You can use LiveData with your ViewModel for this purpose.

Observe the LiveData from your Fragment and once that LiveData provides an update, we'll get it in Fragment. Inside the callback, you can launch from the observing fragment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM