Basic communication between two fragments

前端 未结 10 2155
我寻月下人不归
我寻月下人不归 2020-11-22 05:00

I have one activity - MainActivity. Within this activity I have two fragments, both of which I created declaratively within the xml.

I am trying to pas

10条回答
  •  渐次进展
    2020-11-22 05:27

    There is a simple way to implement communication between fragments of an activity using architectural components. Data can be passed between fragments of an activity using ViewModel and LiveData.

    Fragments involved in communication need to use the same view model objects which is tied to activity life cycle. The view model object contains livedata object to which data is passed by one fragment and the second fragment listens for changes on LiveData and receives the data sent from fragment one.

    For complete example see http://www.zoftino.com/passing-data-between-android-fragments-using-viewmodel

提交回复
热议问题