How to pass and get value from fragment and activity

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

How to pass and get value from fragment and activity?

相关标签:
9条回答
  • 2020-12-25 12:14

    In one source code I found this version:

    class ConfirmPasswordActivity : Activity {
    
    companion object {
        lateinit var person: Person
        fun newIntent(context: Context, person: Person) = run {
            this.person = person
            Intent(context, ConfirmPasswordActivity::class.java)
        }
    }
    private fun setOnClickListeners() {
        ib_back.setOnClickListener { finish() }
        btn_confirm_password.setOnClickListener {
            onNext(UiEvents.OnBtnConfirmClicked(person))
        }
    }
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-12-25 12:27

    Kotlin, Fragment: for pass

    companion object {
        private const val ARGUMENT_ACTION = "ARGUMENT_ACTION"
    
        fun newInstance(action: Int) : MyFragment{
            return MyFragment().apply {
                arguments = bundleOf(ARGUMENT_ACTION to action)
            }
        }
    }
    

    for get

    requireArguments().getInt(ARGUMENT_ACTION)
    
    0 讨论(0)
提交回复
热议问题