How to pass and get value from fragment and activity

前端 未结 9 1252
独厮守ぢ
独厮守ぢ 2020-12-25 11:28

How to pass and get value from fragment and activity?

9条回答
  •  甜味超标
    2020-12-25 12:21

    There is the companion object for that (https://kotlinlang.org/docs/reference/object-declarations.html#companion-objects )

    Define your fragment as usual, and declare the companion that acts as the static newInstance() equivalent in Java :

    class ViewStackListFragment : Fragment() {
      companion object {
            fun newInstance(position: Int): ViewStackListFragment {
                val fragment = ViewStackListFragment()
                val args = Bundle()
                args.putInt("position", position)
                fragment.setArguments(args)
                return fragment
            }
        }
    }
    

    And simply call it like in Java :

    val fragment = ViewStackListFragment.newInstance(4)
    

提交回复
热议问题