Reputation: 9216
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
Reputation: 7494
This should do it for you.
Pagefragment pageFragment = PageFragment.newInstance(value1, value2);
Upvotes: 0
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
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