Home > Software design >  should I use newInstance function somewhere?
should I use newInstance function somewhere?

Time:12-13

I'm new in kotlin and android development.

I was following a tutorial, in that tutorial in a fragment class, companion object, defined a method named newInstance() that returned a fragment, the method was never used.

class myFragment : Fragment(){
    companion object {

        fun newInstance(foo:Int): myFragment {
            val fragment = myFragment()

            val args = Bundle()
            args.putString("foo", foo)
            fragment.arguments = args

            return fragment
        }
    }
}     

Is that okay? Is that going to use it automatically or should I use it somewhere?

(sorry if the explanation isn't good)

CodePudding user response:

It not gonna be used automatically, it is just one of the ways to create fragments. Basically you need to call this function in the place where you wish to add/ replace this fragment into it's container with the help of FragmentManager

CodePudding user response:

You need to use supportFragment manager in your activity to replace the fragment

 val transition = supportFragmentManager.beginTransaction()
 transition.addToBackStack("Your_fragment_unique_tag")
 transition.replace(containerViewId, fragment).commit()

containerViewId will be FrameLayout id in your activity which is the container for replacing fragment i.e R.id.mainContainer

  • Related