How to pass and get value from fragment and activity?
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))
}
}
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)
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)