5
\$\begingroup\$

Android documentation says:

Often you will want one Fragment to communicate with another, for example to change the content based on a user event. All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly.

My question is: Why should Fragments never communicate directly? Because it can cause problems or simply because of "good" code (clean code, maintenance...)?

Fragments communicate directly in my apps and I have not encountered any problem yet. Here an example of how I pass data from an "Event" fragment to a "Event Details" fragment:

public class UpcomingEventsFragment extends Fragment {

    private UpcomingEventsAdapter mAdapter;
    private ListView listview;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_upcomingevents, container, false);
        listview = (ListView) rootView.findViewById(R.id.upcomingevents);
        mAdapter = new UpcomingEventsAdapter(getActivity());
        listview.setAdapter(mAdapter);

        listview.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Event event = mAdapter.getItem(position);
                Bundle args = new Bundle();
                args.putString("id", event.getId());

                EventDetailsFragment fragment = new EventDetailsFragment();
                fragment.setArguments(args);
                FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
                ft.replace(R.id.content_frame, fragment);
                ft.addToBackStack(null);
                ft.commit();
            }
        });

        return rootView;
    }
}
\$\endgroup\$
4
\$\begingroup\$

As the Fragments doc says:

You can think of a fragment as a modular section of an activity

A fragment that assumes the existence of another fragment breaks the modularity. Fragments should be unaware of each other, be self-contained and work independently.

Take for example the common use case when the activity uses a single small fragment on phones, and +1 larger fragment on tablets. The smaller fragment should not access the larger one directly because it may not be there. You might say the large fragment could safely assume the smaller one always exists, but that too would violate the modularity principle.

When your app is perfectly modular, fragments don't know about each other. You can add a fragment, remove a fragment, replace a fragment, and they should all work fine, because they are all independent, and the activity has full control over the configuration.

\$\endgroup\$
  • \$\begingroup\$ But in my case, I don't use fragments to handle different layouts. I use them for Navigation Drawer so they are supposed to always exist. I have 1 Activity with multiple fragments. \$\endgroup\$ – Ismael Apr 20 '14 at 23:10
  • \$\begingroup\$ In terms of the modular design principle, making fragments independent from each other seems to make good sense. But if you are 200% sure your fragments can always count on each other, then maybe it's ok to make an exception in your case. \$\endgroup\$ – Stop ongoing harm to Monica Apr 20 '14 at 23:16
  • \$\begingroup\$ Thanks for your clarification. So, regarding of the different answers, it's only for "best practice". \$\endgroup\$ – Ismael Apr 20 '14 at 23:43
6
\$\begingroup\$

Android application design best practices suggest that fragments should be modular and independent from each other, so that you may able to arrange them differently - not just on screen, but also changing relationships among them - when you are targeting devices with widely different screen sizes, e.g. smartphones and tablets. Those very same best practices suggest that you don't see nor use the whole activity interface in a fragment, but only a subset that you have defined through a proper custom interface, which typically contains callback methods that are invoked in cases such as yours, when an action taken in a fragment must trigger the creation and display of another fragment.

However, note that there is an interesting API that has been thought exactly for the purpose of starting a fragment from another fragment, and possibly returning a result to the caller fragment, much like startActivity and onActivityResult do for activities. I do believe that, while modularity and independence are indeed best design practices, there may be cases when two fragments are strictly intertwined, so much that that dependency is preserved even on different devices; and the cited API is there to help.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.