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 pass the String
of text input by the user into Fragment A
to the text view in Fragment B
. However this is proving to be very difficult. Does anyone know how I might achieve this?
I am aware that a fragment can get a reference to it's activity using getActivity()
. So I'm guessing I would start there?
Have a look at the Android developers page: http://developer.android.com/training/basics/fragments/communicating.html#DefineInterface
Basically, you define an interface in your Fragment A, and let your Activity implement that Interface. Now you can call the interface method in your Fragment, and your Activity will receive the event. Now in your activity, you can call your second Fragment to update the textview with the received value
Your Activity implements your interface (See FragmentA below)
Fragment A defines an Interface, and calls the method when needed
Fragment B has a public method to do something with the text
Some of the other examples (and even the documentation at the time of this writing) use outdated
onAttach
methods. Here is a full updated example.Notes
Code
MainActivity.java
GreenFragment.java
BlueFragment.java
XML
activity_main.xml
fragment_green.xml
fragment_blue.xml
Learn " setTargetFragment() "
Where " startActivityForResult() " establishes a relationship between 2 activities, " setTargetFragment() " defines the caller/called relationship between 2 fragments.
I recently created a library that uses annotations to generate those type casting boilerplate code for you. https://github.com/zeroarst/callbackfragment
Here is an example. Click a
TextView
onDialogFragment
triggers a callback toMainActivity
inonTextClicked
then grab theMyFagment
instance to interact with.}
Consider my 2 fragments A and B, and Suppose I need to pass data from B to A.
Then create an interface in B, and pass the data to the Main Activity. There create another interface and pass data to fragment A.
Sharing a small example:
Fragment A looks like
FragmentB looks like
Main Activity is
The nicest and recommended way is to use a shared ViewModel.
https://developer.android.com/topic/libraries/architecture/viewmodel#sharing
From Google doc:
ps: two fragments never communicate directly