Luke Needham
Luke Needham

Reputation: 3989

Can we pass arguments to Fragments more beautifully?

For every Fragment class I make, I add something like this:

companion object {
    private const val PARAMETER_1 = "parameter1"
    private const val PARAMETER_2 = "parameter2"

    fun newInstance(parameter1: String, parameter2: Int) = MyDialog().apply {
        arguments = bundleOf(
            PARAMETER_1 to parameter1,
            PARAMETER_2 to parameter2)
    }
}

And then I add:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    val args = arguments ?: return

    property1 = args[PARAMETER_1]
    property2 = args[PARAMETER_2]
}

This isn't horrific. But it is boilerplate that it would be great to get rid of.

Here's my attempt so far:

abstract class BaseFragment : Fragment() {
  abstract val constructorArguments: List<KMutableProperty<*>>

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    val args = arguments ?: return

    constructorArguments.forEach {
        val key = keyPrefix + it.name
        val argument = args.get(key)
        val clazz = it.javaClass
        val typedArgument = clazz.cast(argument)
        it.setter.call(typedArgument)
    }
  }

  companion object {
    const val keyPrefix = "ARGUMENT_"

    fun newInstance(fragment: BaseFragment, vararg parameters: Any): BaseFragment {
        val constructorArguments = fragment.constructorArguments
        val parameterMap = mutableListOf<Pair<String, Any?>>()
        constructorArguments.forEachIndexed { index, kMutableProperty ->
            val key = keyPrefix + kMutableProperty.name
            val parameter = parameters[index]
            parameterMap.add(Pair(key, parameter))
        }
        val args = bundleOf(*parameterMap.toTypedArray())
        fragment.arguments = args
        return fragment
    }
  }
}

And then, in the actual fragment I can just have:

class MyFragment : BaseFragment() {

  lateinit var myProperty: String

  override val constructorArguments = listOf<KMutableProperty<*>>(
    ::myProperty
  )

  companion object {
    fun newInstance(argument: String) = BaseFragment.newInstance(MyFragment(), argument)
  }
}

This approach is far from perfect - especially the:

val parameter = parameters[index]

Does anyone know a better way to do this? Do you have some suggestions for how my approach can be improved? Or is this whole idea doomed to fail, and have I wasted a morning?

Upvotes: 0

Views: 2990

Answers (2)

EpicPandaForce
EpicPandaForce

Reputation: 81529

You can have a base fragment that defines a common args parameter

abstract class BaseFragment : Fragment() {
    companion object {
        const val ARGS_KEY = "__ARGS__"
    }

    fun <T: Parcelable> getArgs(): T = requireArguments().getParcelable(ARGS_KEY)

    fun putArgs(args: Parcelable): Bundle = (arguments ?: Bundle()).apply {
        putParcelable(ARGS_KEY, args)
    }
}

Then

@Parcelize data class Args(val parameter1: String, val parameter2: Int)

companion object {
    fun newInstance(args: Args) = MyDialog().apply {
        putArgs(args)
    }
}

And now you can do it like

class MyFragment: BaseFragment() {
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        val args: Args = getArgs()
        args.parameter2
    }
}

Upvotes: 1

Luke Needham
Luke Needham

Reputation: 3989

An 'answer' to this question is to use the Android Jetpack Navigation library. It provides SafeArgs, which greatly simplifies passing arguments to Fragments. See:

https://developer.android.com/guide/navigation/navigation-pass-data#Safe-args

Upvotes: 1

Related Questions