Kotlin - idiomatic way to create a Fragment newInstance pattern

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

    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)
        }
    }
    
    0 讨论(0)
  • 2020-12-29 20:01
    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)
      } 
    }
    
    0 讨论(0)
  • 2020-12-29 20:03
    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

    0 讨论(0)
  • 2020-12-29 20:08

    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()
        }
    }
    
    0 讨论(0)
  • 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 : 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.

    0 讨论(0)
  • 2020-12-29 20:14

    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
        }
        ...
      }
      ...
    }
    
    0 讨论(0)
提交回复
热议问题