Home Ask Login Register

Developers Planet

Your answer is one click away!

davioooh February 2016

Passing parameters to Fragment at creation time

I'm new to Android programming and I'm studying some components and architecture.

I'm now testing Fragments.

I need to pass a List of custom objects from my Activity to a nested Fragment.

I read this question: How to pass a variable from Activity to Fragment, and pass it back? and I noticed that the Bundle collection is the best practice to pass parameters during fragment creation.

Bundle bundle = new Bundle();
String myMessage = "Stackoverflow is cool!";
bundle.putString("message", myMessage );
FragmentClass fragInfo = new FragmentClass();

But I'm wondering why can't I simply pass my parameters via constructor, say:

List<CustomObject> myParameter = new ArrayList<CustomObject>();
MyFragment fragInfo = new MyFragment(myParameter); // custom Fragment constructor

Is this a wrong approach? Is the empty constructor used by the framework to instantiate the fragment via reflection or something similar?


Jörn Buitink February 2016

At the time when Android wants to recreate the fragment (i.e. app comes from background to foreground), it will use the default no-argument constructor (without parameters). So you should not overload the constructor.

Post Status

Asked in February 2016
Viewed 1,583 times
Voted 12
Answered 1 times


Leave an answer

Quote of the day: live life