2

What is the difference between

Intent i = new Intent(getActivity(), HomeworkPagerActivity.class);
i.putExtra(HomeworkFragment.EXTRA_HOMEWORK_ID, c.getId());
startActivity(i);

and:

HomeworkFragment newFragment = new HomeworkFragment();
Bundle args = new Bundle();
args.putInt(HomeworkFragment.ARG_POSITION, position);
newFragment.setArguments(args);

FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);

transaction.commit();

I'm using a Fragment to launch another Fragment.

However, which one should be used and why?

Additionally, I need to transmit data from the child Fragment (HomeworkFragment) back to the Fragment that launched it in the first place. Which setup allows data (like an id number) to be transmitted easily?

Squonk
  • 48,735
  • 19
  • 103
  • 135
waylonion
  • 6,866
  • 8
  • 51
  • 92
  • "which one should be used and why?" : IMHO you should use neither of them. The design philosophy for Fragments is that they should be self-contained and re-usable. If a `Fragment` "knows" about a particular `Activity` or another `Fragment` you've broken that model. As Little Child mentions, your Fragments can define interfaces and use those to communicate with the parent `Activity` and that should allow indirect control and communication. – Squonk Sep 01 '14 at 18:53

2 Answers2

2

Okay, look.

Intent i = new Intent(getActivity(), HomeworkPagerActivity.class);
i.putExtra(HomeworkFragment.EXTRA_HOMEWORK_ID, c.getId());
startActivity(i);  

This starts a whole new Activity with it's own lifecycle. Where as this:

FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); 

transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null); 

transaction.commit();   

replaces a Fragment in R.id.fragment_container with newFragment.


However, which one should be used and why?

Depends on your needs.

Additionally, I need to transmit data from the child Fragment (HomeworkFragment) back to the Fragment that launched it in the first place. Which setup allows data (like an id number) to be transmitted easily?

Assuming you have two Fragments, you can use interfaces to transmit the data back to the activity first and then to the second fragment.

An SO User
  • 24,612
  • 35
  • 133
  • 221
1

One starts an activity.

The other instantiates and attaches a fragment to fragment_container which is a part of the calling activity's layout.

Simas
  • 43,548
  • 10
  • 88
  • 116