The best practice on Android for creating a Fragment
is to use a static factory method and pass arguments in a Bundle
via setArguments()
I like to do it this way:
companion object {
private const val MY_BOOLEAN = "my_boolean"
private const val MY_INT = "my_int"
fun newInstance(aBoolean: Boolean, anInt: Int) = MyFragment().apply {
arguments = Bundle(2).apply {
putBoolean(MY_BOOLEAN, aBoolean)
putInt(MY_INT, anInt)
}
}
}
Edit: with KotlinX extensions, you can also do this
companion object {
private const val MY_BOOLEAN = "my_boolean"
private const val MY_INT = "my_int"
fun newInstance(aBoolean: Boolean, anInt: Int) = MyFragment().apply {
arguments = bundleOf(
MY_BOOLEAN to aBoolean,
MY_INT to anInt)
}
}
companion object {
private const val NOTE_ID = "NOTE_ID"
fun newInstance(noteId: Int?) = AddNoteFragment().apply {
arguments =
Bundle().apply { putInt(NOTE_ID, noteId ?: Int.MIN_VALUE) }
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
arguments?.let {
noteId = it.getInt(NOTE_ID)
}
}
inline fun <reified T : Fragment>
newFragmentInstance(vararg params: Pair<String, Any>) =
T::class.java.newInstance().apply {
arguments = bundleOf(*params)
}`
So it is used like that:
val fragment = newFragmentInstance<YourFragment>("key" to value)
Credit
bundleOf()
can be taken from Anko
Kotlin package-level function
What about about that kotlin says to use package level function instead of “static” method
MyFragment.kt
class MyFragment : Fragment() {
.....
}
fun MyFragmentNewInstance(): MyFragment {
return MyFragment()
}
MyActivity.kt
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (supportFragmentManager.findFragmentById(R.id.fragmentContainer) == null) {
supportFragmentManager.beginTransaction()
.add(R.id.fragmentContainer, MyFragmentNewInstance())
.commit()
}
}
Late to the party, but I believe Idiomatically it should be something like this:
private const val FOO = "foo"
private const val BAR = "bar"
class MyFragment : Fragment() {
companion object {
fun newInstance(foo: Int, bar: String) = MyFragment().withArgs {
putInt(FOO, foo)
putString(BAR, bar)
}
}
}
With an extension like this:
inline fun <T : Fragment> T.withArgs(argsBuilder: Bundle.() -> Unit): T =
this.apply {
arguments = Bundle().apply(argsBuilder)
}
or
companion object {
fun newInstance(foo: Int, bar: String) = MyFragment().apply {
arguments = bundleOf(
FOO to foo,
BAR to bar
)
}
}
The key being that the private constants should not be part of the companion object.
Another way of doing this I found here
class MyFragment: Fragment(){
companion object{
private val ARG_CAUGHT = "myFragment_caught"
fun newInstance(caught: Pokemon):MyFragment{
val args: Bundle = Bundle()
args.putSerializable(ARG_CAUGHT, caught)
val fragment = MyFragment()
fragment.arguments = args
return fragment
}
...
}
...
}