0

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();
fragInfo.setArguments(bundle);

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?

Community
  • 1
  • 1
davioooh
  • 23,742
  • 39
  • 159
  • 250
  • You are right. And they can't make any assumption on the number and type of the arguments of your constructor – Blackbelt Feb 08 '16 at 14:34

1 Answers1

2

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.

Jörn Buitink
  • 2,906
  • 2
  • 22
  • 33