I have a scenario with Activity A having tabs, Fragment 1,2,3,4. Here Fragment 2 opens Activity B which has multiple Fragments 1,2,3,4. Now from Activity B (Fragment 4), I want to send a result back to Activity A's Fragment 2 which was there in the background. What will be the best way to do that?
Currently, I am thinking to use Result API to open Activity B, and from Fragment 4 of Activity B, set Result somehow(now sure how). Should I set the result in Activity B first, which will then set the result for Activity A's Fragment 2?
CodePudding user response:
Best Way to communicate between two Fragment A and Fragment B is through viewModel ViewModel is created and share between two fragment , you set value from Fragment A and access the value using getValue() method in Fragment B . ViewModel share same instance with both fragments
CodePudding user response:
There are 2 pretty simple solutions:
send an
Intent
from any activity or fragment (in your case, from Activity B Fragment 4), and set up an intent filter in your Activity A to receive that intent. You'll have to process that intent in Activity A'sonNewIntent()
, and then forward the data to whichever fragment you wantUse a lifecycle component, like
LiveData
to do it. You'll want to set either a Singleton class in Java or an Object in Kotlin, and then create theLiveData
variable inside that class. And you can then set your Activity B to update thatLiveData
variable, and set your Activity A to observe it for changes