Sharing data between Fragment and Activity
Sharing data between Fragment and Activity
Overview
This Blog introduces how to pass data from Fragment
to Activity
. (Fragment -> Activity)
If you have an Activity
, which contains two Fragment
, one is FragmentA
, other is FragmentB
. You want Activity to know the variable setting in FragmentA
and notify the FragmentB
.
Concrete step
Fragment -> Activity
- In your Fragment : create an interface with getter and setter methods.
- In your Activity : implement the interface.
In FragmentA
In this example, the text
variable is the data we want to share with Activity.
Firstly, create a listener interface in FragmentA
and override the onAttach()
.
public static class FragmentA extends Fragment {
private OnSomethingSelectedListener listener;
...
// Container Activity must implement this interface
public interface OnSomethingSelectedListener {
public void onSomethingSelected(String text);
}
...
// onAttach() is called when a fragment is first attached to its activity.
// onCreate(Bundle) will be called after this.
@Override
public void onAttach(Context context) {
super.onAttach(context);
try {
listener = (OnSomethingSelectedListener) context;
} catch (ClassCastException e) {
// If Activity don't implement the OnSomethingSelectedListener interface
throw new ClassCastException(context.toString() + " must implement OnSomethingSelectedListener");
}
}
...
}
And then ,you should add the following code in FragmentA
:
public static class FragmentA extends Fragment {
private OnSomethingSelectedListener listener;
...
// To pass data to Activity, when something happen.
public void onSomethingClick(String text) {
// Send the text to the host activity
// It will invoke the method in Activity
listener.onSomethingSelected(text);
}
...
}
In host Activity
you should implement the interface created in FragmentA
.
public class HostActivity extends AppCompatActivity implements FragmentA.OnSomethingClickListener {
private String text;
...
// You will invoke this method in FragmentA.
@Override
public void onSomethingClicked(String text) {
// 'text' variable is passed from FragmentA.
this.text = text;
//...
}
...
}
Summary
The key point of this approach is to get the reference of host Activity so that you can invoke the method in Activity to keep data in host Activity's.
This is not the only one way to achieve. You also can use ViewModel
to do it. More about it please read the Android Official Document about Fragment communicate. (see https://developer.android.com/guide/fragments/communicate)