Kotlin - idiomatic way to create a Fragment newInstance pattern

前端 未结 6 1857
灰色年华
灰色年华 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:13

    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.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.

提交回复
热议问题