Fcoder
Fcoder

Reputation: 9216

calling fragment and passing parameters

I have a fragment with this initializing:

    public static final PageFragment newInstance(int id,long stage_count){
    PageFragment fragment=new PageFragment();
    final Bundle args = new Bundle(2);
    args.putInt("EXTRA_ID", id);
    args.putLong("EXTRA_COUNT", stage_count);
    fragment.setArguments(args);

    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.id = getArguments().getInt("EXTRA_ID");
    this.stage_count = getArguments().getLong("EXTRA_COUNT");
}

my problem is how i can call it? for example i want to instantiate this fragment and pass that two parameters. in regular way i does this:

PageFragment fragment=new PageFragment(1,1);

But now how i can do this?

Upvotes: 0

Views: 76

Answers (4)

ucsunil
ucsunil

Reputation: 7494

This should do it for you.

Pagefragment pageFragment = PageFragment.newInstance(value1, value2);

Upvotes: 0

Code-Apprentice
Code-Apprentice

Reputation: 83517

The common pattern is to create a static method named newInstance() inside your fragment subclass. This acts as the constructor and encapsulates creating the arguments Bundle and calling setArguments().

You cannot pass the arguments through a regular constructor because of the design.

Upvotes: 0

Andrew Carl
Andrew Carl

Reputation: 822

Actually,if you extend Fragment and declare any constructor ,you will be given a warning because when the system restores a fragment (e.g on config change), it will automatically restore your bundle. From your aspect,it is ok to pass parameters in constructor .

However if a fragment is instanced in constructor with paramerers, thoese wont be restored

Upvotes: 0

chessdork
chessdork

Reputation: 2019

Try:

PageFragment fragment = PageFragment.newInstance(1,1);

Upvotes: 1

Related Questions