简体   繁体   中英

How do I update new data in ViewPager2 fragments?

I have a Fragment that contains:

  • A ViewPager2 which holds several Fragments for left-right swiping
  • These Fragments only contains a RecyclerView which displays a list of items in it
  • A custom view (LinearLayout)

What I want to achieve is when user click on the custom view, it will update the data in the RecyclerView.

In my case, when a user unselects an item in the custom view, it will also unselect what is inside the RecyclerView items.

I'm not sure how to do this with a listener that goes back down to the RecyclerView's Adapter level. Anyone have any idea on how to achieve this?

you can use BroadcastReceiver for this. In cases you want to trigger, when you broadcast, the relevant code will be triggered on the Fragment you want to capture the broadcast.

You can also use the EventBus library. Both methods will work, but the EventBus manufacturer claims that they are more performant than BroadcastReceiver.

You can communicate using:

  1. SharedViewModels: Both Fragments use same SharedViewModel, 1 will update the Observable(LiveData/Flow) in viewModel and another fragment will observe the changes for that Observable(LiveData/Flow)

  2. Flows/LiveData: exposed from any Repository or UseCase layer Similar to SharedViewModels, but your Observable(LiveData/Flow) will be in either Repository or UseCase and your both viewModels of both fragments will be injecting same Repository/UseCase.

  3. RoomDB: Store that data in RoomDB and return Flow/LiveData from Room DAO. And observe this flow in your fragment. Whenever the DB changes, your fragment will be notified with updated data.

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