Kotlin - idiomatic way to create a Fragment newInstance pattern

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

    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)
      } 
    }
    

提交回复
热议问题