Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

android - 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...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...