kirtan403
kirtan403

Reputation: 7421

Passing arguments bundle to Fragment

I need to pass some variable from activity to fragment inside a tab layout. I found there are 2 preferred ways of passing argument bundles to the fragment by its initialization methods for the tab layout.

  1. By creating static newInstance() method and providing details.
  2. Creating instance of fragment inside FragmentPagerAdapter

But, I have some doubts how this works.

If I create this this is:

public class SectionsPagerAdapter extends FragmentPagerAdapter {
    MyFragment myFragment;

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);

        myFragment = new MyFragment();
        Bundle args = new Bundle();
        args.putString("id", id);
        myFragment.setArguments(args);
    }

    // ... 
 }

Here I am creating the instance of fragment and setting its argument afterwords.

And if I create it in newInstance() method something like this:

public static MyFragment newInstance(String id) {
    MyFragment myFragment = new MyFragment();
    Bundle args = new Bundle();
    args.putString("id", id);
    myFragment.setArguments(args);

    return myFragment;
}

Some doubts:

  1. When will the onCreate() or onCreateView() will be called? What if after line new MyFragment() and before setting bundle?

  2. Is there any possibility where getArguments can return null?

  3. In both ways I am doing the same thing. Setting args after new MyFragment() call. How late I can set the arguemnts. Is it necessary to set arguments exactly after the new MyFragment() call?

Sorry, if I asked some silly question. But I am new to Fragments. Thanks :)

Upvotes: 2

Views: 3037

Answers (1)

gitter
gitter

Reputation: 1726

onCreate() and onCreateView() will be called sometime after you've committed the fragment transaction. i.e. called commit(). And you set bundle before that.

As long as you're setting bundle before commit, getArguments shouldn't be null.

Both are doing the same thing. In 1st you're creating the fragment instance by yourself and setting bundle yourself. In 2nd you're using what is called a factory method (Effective Java Item 2) which is managed by your fragment. So it's difficult to make mistake in 2nd as arguments are always set.

Upvotes: 2

Related Questions