DEV Community

Randy Arba
Randy Arba

Posted on • Edited on

You can add constructor in new version of fragment

Fragment Factory help you create Constructor

Developer right now cannot add constructore in fragment, this advise come from officially google, when we still create constructore our IDE lint will show warning that suggest us to remove it. Constructor contain argument that will be execute in our fragment and we can create some dependecies injection, But we cant do that. Until now, We still face that we cannot add argument constructor when we initialise fragment. Until we meet the Fragment Factory, Fragment Factory will give you manage/control to build fragment and enable constructor.

Take a look this code, we just need to subclass Fragment Factory and we need customize the implementation and no need use Fragment. After that we must tell the Fragment manager to use this class to initialize the fragment.


class MyFragmentFactory (
    private val requestService: RequestService
) : FragmentFactory() {

    override fun instantiate(classLoader: ClassLoader, className: String): Fragment { ... }

}

// Your Activity
class MainActivity : AppCompatActivity() {

    @Inject
    lateinit var fragmentFactory: MyFragmentFactory

    override fun onCreate(savedInstanceState: Bundle?) {
        supportFragmentManager.fragmentFactory = fragmentFactory
        super.onCreate(savedInstanceState)
        ...
    }
}

Enter fullscreen mode Exit fullscreen mode

Thanks to android community that can add this, basically this feature come and introduce in AndroidDevSummit last week ago. This release has some new overloads to enable you pass generic class into Fragment Factory to manage creating instace of fragment.

supportFragmentManager.beginTransaction()
                .replace(R.id.fragment_container, SecondFragment::class.java, args = null)
                .commitAllowingStateLost()
Enter fullscreen mode Exit fullscreen mode

If you want try it before stable you can add this into your build.gradle in level app.

def fragment_version = "1.2.0-rc01"
  implementation "androidx.fragment:fragment-testing:$fragment_version"
  implementation "androidx.fragment:fragment-ktx:$fragment_version"
Enter fullscreen mode Exit fullscreen mode

Top comments (0)