Transferring data between fragment view modes

Let me directly say that this is rather a “structural” question, and I am not asking anyone to write code; I'm just trying to figure out how I should structure my application.

I am using Android DrawerLayout/ NavigationViewfor my application. This means that it MainActivityis the host for all my fragments.

I currently have three fragments (actually it is a lot more, but they are more or less exactly similar to these three fragments, only for different data sets).

  • Listfragment
  • DetailFragment
  • EditFragment (used to add and edit)

On mine ListFragmentI have (surprise!) A list of items. This is a collection LiveDataon SharedViewModel(linked to a MainActivitylife cycle). When an element is being listened, I pass the event through MainActivityusing the interface listener.

MainActivitythen loads DetailFragment. In the same call, I load an instance SharedViewModel(again bound to MainActivity). I installed SharedViewModel.selectedItemas a knocked item. Then in the function, DetailFragment onCreateI get the selected item through ViewModelProviders.of(activity).get(SharedViewModel::class.java).selectedItem.

There DetailFragmentis an edit button on. This goes through more or less the same procedure described above, but instead loads EditFragment. When the edited / added item is saved, I add / replace the item in the collection SharedViewModelthrough the interface listener MainActivity.

, . -, , , MainActivity ( , ). , MainActivity - , .

, , ListFragmentViewModel, ListFragment. DetailFragmentViewModel, EditFragmentViewModel ..

, , . , , EditFragment. ListFragmentViewModel? ListFragment back-stack, viewmodel , , . , , ( , , DetailFragment ListFragment?), , .

, (, DetailFragmentViewModel.)

, . - ?

+4
1

, EditFragment. ListFragmentViewModel?

EditFragment : "yo! !". , , (, RxJava PublishSubject). ListFragmentViewModel .

ListFragment back-stack, viewmodel , ,

, , . . . , - .

+4

Source: https://habr.com/ru/post/1692644/


All Articles