Kotlin - idiomatic way to create a Fragment newInstance pattern

前端 未结 6 1867
灰色年华
灰色年华 2020-12-29 19:27

The best practice on Android for creating a Fragment is to use a static factory method and pass arguments in a Bundle via setArguments()

6条回答
  •  没有蜡笔的小新
    2020-12-29 20:03

    inline fun 
        newFragmentInstance(vararg params: Pair) =
        T::class.java.newInstance().apply {
            arguments = bundleOf(*params)
        }`
    

    So it is used like that:

    val fragment = newFragmentInstance("key" to value)
    

    Credit

    bundleOf() can be taken from Anko

提交回复
热议问题