Fragment Communication

Activity can send data to Fragment and receive data from Fragment

All Fragment-to-Fragment communication is done through host Activity

RatingFragmentSetup

Add a Stringvariable and float value, we will be using this to place inside the Bundle

Define a listener interface called OnFragmentInteractionListener. In it, specify a callback method that you will create, called onRadioButtonChoice():

Add a variable for the listener later

Override the onAttach() lifecycle method in SimpleFragment to capture the host Activity interface implementation:

The onAttach() method is called as soon as the Fragment is associated with the Activity. The code makes sure that the host Activity has implemented the callback interface. If not, it throws an exception.

The string resource exception_message is included in the source code for the text "must implement OnFragmentInteractionListener"

Overall, your class should end up looking like this.

Implementing OnFragmentInteractionListener

Now that we have set up our RatingListener for communication. We need to implement the OnFragmentInteractionListener in the activity in order to receive data from fragment

Add a member variable in MainActivity for the choice the user makes with the RatingBar, and set it to the default value

Set up the onSaveInstanceState(Bundle) to save our float variable and states for the Activity

The app should now show a toast when you click it.

Providing user's choice to fragment (Main

We have to now set a Bundle and use the Fragment.setArguments(Bundle) method to supply the construction arguments for the Fragment.

A Bundle is like a key-value dictionary which allows to transfer information to other activities, fragments.

First, let's setup a newInstance() method to use a Bundle and setArguments

Add following code to onCreateView() method to retrieve the previously set value of choice

Lastly, we need to change our functions in MainActivity to RatingFragment.newInstance(mRatingChoice);

Your app should be communicating the choice from the Fragment to the Activity, and then back to the Fragmentwhich should display the choice you made previously always

End Result:

From this point, there are more complicated paths and communications you can perform, but these steps lay a foundation in using them.

Last updated