Pass data between Fragments

1

I have done a ViewPager, with tabs to navigate between the different fragments (3).

My idea was to have in the first fragment a list of CheckBox with the names of companies, and that when you slide to the second fragment, in which I have a map (using the Google Maps API), the thumbtacks will be marked according to the CheckBox that are selected in the first fragment.

The fact is that I do not know how to pass data from one fragment to another.

Between activitys if I created an Intent and made putExtra() and getExtra() and that ... but between fragments I do not know how it is done.

    
asked by Jose Manuel Yébenes 07.04.2017 в 13:17
source

1 answer

1

In the documentation you have the article: Communicating with Other Fragments

One solution would be to send the data by means of a interfaz :

public class HeadlinesFragment extends ListFragment {
    OnHeadlineSelectedListener mCallback;

    // Container Activity must implement this interface
    public interface OnHeadlineSelectedListener {
        public void onArticleSelected(int position);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try {
            mCallback = (OnHeadlineSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnHeadlineSelectedListener");
        }
    }

    ...
}

and another way to send data between Fragments is to send your bundle, or data when instances other Fragment :

public class myFragment {

public static myFragment newInstance(@NonNull final ArrayList<String> fooList) {
    myFragment f = new myFragment();
    Bundle args = new Bundle(); //* Bundle a recibir con datos.
    args.putParcelableArrayList(“my_key”, fooList);
    f.setArguments(args);
    return f;
} 


public ArrayList<String> getFoo() {
    final Bundle bundle = getArguments();
    bundle != null ? bundle.getParcelableArrayList("mi_llave") : null;
   }
}
    
answered by 07.04.2017 в 16:48