Home > database >  How can I access and use button of one fragment inside another fragment?
How can I access and use button of one fragment inside another fragment?

Time:10-31

I've one fragment, HomeFragment(). In this fragment I've TabLayout with ViewPager2. In viewPager2 there is another fragment called ordersFragment(). Is it possible that I can click on any button that is placed in HomeFragment() and display some text in ordersFragment()`?

CodePudding user response:

I'd really recommend using the modern approach, which is the ViewModels component. A view model is basically a class that holds your data and state, and the component enables each fragment in your activity to fetch the same view model instance, so they're all looking at the same thing

That way, one fragment can set a value for some data, while another fragment observes it and gets notified whenever there's an update. Neither fragment needs to know about each other, they're just talking to the view model and observing the stuff they need to worry about. There's an example of this kind of thing in the docs

You can coordinate all this stuff yourself (e.g. by going through the parent Activity and making that talk to the other fragment) but you're adding a lot of work and boilerplate which ViewModels take care of for you. And it helps you to separate your UI (displaying stuff, handling user interactions) from the business logic (doing something with that data, updating the app state). It's definitely good to know and makes communication around your app a lot easier

CodePudding user response:

The best practice is to use callback implemented in one fragment and call that in another fragment.

if you are using kotlin check this..

link (i don't want to copy paste same code here)

  • Related