Quinn
Quinn

Reputation: 9476

Can I put arguments in my Fragments constructor

So I have a fragment like this:

class MyFragment(val thing: SomeDataObject) : Fragment {

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        // do stuff using `thing`
    }

}

And I create and attach it like this:

val myFragment = MyFragment(SomeDataObject())

supportFragmentManager.beginTransaction()
    .replace(R.id.contentFrame, myFragment)
    .commit()

Where I take a variable thing as a parameter - this seems to work, however everything I read about passing arguments to fragments says to do it by creating a bundle and setting arguments on the fragment instance.

Is there something wrong with doing it the way I defined above or some kind of benefit to using bundles instead?

Just curious as to why everywhere else suggests using seemingly over complicated ways of passing the arguments...

Upvotes: 0

Views: 1553

Answers (2)

Ayush
Ayush

Reputation: 160

Android also allows to set FragmentFactory, which will be responsible for instantiating Fragments.

Using fragmentFactory makes sure necessary dependency particularly when dependency is not of primary types and can be put into bundle and set to fragment args.

This also prevents run time exception for activity recreate scenario (screen rotation/screen-zoom etc.)

Can look at this tutorial on how to use a fragmentFactory for parametrized fragment constructor scenario.

Upvotes: 0

laalto
laalto

Reputation: 152907

Fragments need to have a 0-arg constructor so the framework can recreate them for you e.g. after a configuration change. You'll get a crash if the 0-arg constructor is missing. If you have both 0-arg and >0-arg constructors, any init done in the >0-arg one will be missing when the 0-arg constructor is invoked.

Upvotes: 7

Related Questions