Home > database >  How to pass a Fragment as an argument
How to pass a Fragment as an argument

Time:02-03

A summary of what I wanted to do: I want to create an app with tabs but I'll let the users have a setting where they can choose which couple of tabs do they want to use and in what order would they be.

So I thought I would create an ArrayList of all the possible Fragments and make a new ArrayList based on the user's settings. Now, I created a data class to store some details related to the Fragments, which I also set as the type for the ArrayList, and realized that I can't just pass a Fragment as an argument. Passing a regular Fragment makes Android Studio complain that I would want to use a [FragmentName].Companion instead. Accepting the suggestion makes the parameter exactly equal to [FragmentName].Companion, so I can't use it for other Fragments.

So, how do I do that? Or if you got better ideas on how I could structure the app, please let me know.

CodePudding user response:

I would recommend passing only information about how to create fragments, for example, you can go with creating some FragmentDefinition class that will contain more data required to properly create fragments. for example class name, and bundle with parameters. So you can easily instantiate fragments without needing to know additional details.

data class FragmentDefinition(val className: String, val parameters: Bundle): Parcelable

fun sample(){
    val fragmentDefinitions = listOf(
        FragmentDefinition("com.sample.FragmentA", Bundle()),
        FragmentDefinition("com.sample.FragmentB", Bundle()),
        FragmentDefinition("com.sample.FragmentC", Bundle())
    )
    
    fragmentDefinitions.forEach { definition ->
        val fragment = supportFragmentManager.fragmentFactory.instantiate(this::class.java.classLoader!!,definition.className)
        fragment.arguments = definition.parameters
        
        // add your fragment to hierarchy
   }
}
  • Related