38

How to pass and get value from fragment and activity?

A-Sharabiani
  • 17,750
  • 17
  • 113
  • 128
Best Best
  • 515
  • 2
  • 8
  • 17
  • 1
    duplicate Question with https://stackoverflow.com/questions/17436298/how-to-pass-a-variable-from-activity-to-fragment-and-pass-it-back – faraz khonsari Oct 03 '17 at 18:37
  • 1
    Possible duplicate of [How to pass a variable from Activity to Fragment, and pass it back?](https://stackoverflow.com/questions/17436298/how-to-pass-a-variable-from-activity-to-fragment-and-pass-it-back) – zsmb13 Oct 03 '17 at 18:46

10 Answers10

75

Here is the Android Studio proposed solution (= when you create a Blank-Fragment with File -> New -> Fragment -> Fragment(Blank) and you check "include fragment factory methods").

Put this in your Fragment:

class MyFragment: Fragment {

...

    companion object {

            @JvmStatic
            fun newInstance(isMyBoolean: Boolean) = MyFragment().apply {
                arguments = Bundle().apply {
                    putBoolean("REPLACE WITH A STRING CONSTANT", isMyBoolean)
                }
            }
     }
}

.apply is a nice trick to set data when an object is created, or as they state here:

Calls the specified function [block] with this value as its receiver and returns this value.

Then in your Activity or Fragment do:

val fragment = MyFragment.newInstance(false)
... // transaction stuff happening here

and read the Arguments in your Fragment such as:

private var isMyBoolean = false

override fun onAttach(context: Context?) {
    super.onAttach(context)
    arguments?.getBoolean("REPLACE WITH A STRING CONSTANT")?.let {
        isMyBoolean = it
    }
}

Enjoy the magic of Kotlin!

halfer
  • 19,824
  • 17
  • 99
  • 186
Paul Spiesberger
  • 5,630
  • 1
  • 43
  • 53
20

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)
NSimon
  • 5,212
  • 2
  • 22
  • 36
10

use this to send arguments to fragment

fun newInstance(index: Int): MyFragment {
    val f = MyFragment ()
    // Pass index input as an argument.
    val args = Bundle()
    args.putInt("index", index)
    f.setArguments(args)
    return f
}

And get those arguments like this

val args = arguments
val index = args.getInt("index", 0)
Ankit Kumar
  • 3,663
  • 2
  • 26
  • 38
8

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

Do it in more Kotlin style

1) Create an inline function:

inline fun <FRAGMENT : Fragment> FRAGMENT.putArgs(argsBuilder: Bundle.() -> Unit): FRAGMENT = this.apply { arguments = Bundle().apply(argsBuilder) }

2) Now you can use this extension in all fragments without duplication of code:

class MyFragment: Fragment() {
    companion object {
        fun newInstance(name: String) = MyFragment().putArgs {
             putString("nameKey", name)
        }
    }
}

class MyFragment1: Fragment() {
     companion object {
         fun newInstance(boolean: Boolean) = MyFragment1().putArgs {
              putBoolean("booleanKey", boolean)
         }
     }
}

3) Create your fragments:

val myFragment = MyFragment.newInstance("NAME")
val myFragment1 = MyFragment1.newInstance(true)
Krasavello13
  • 313
  • 5
  • 9
2

To pass and get value from fragment and activity,

val mFragment = Fragment()
val mArgs = Bundle()
mArgs.putInt("Key", value)
mFragment.setArguments(mArgs)

Use this piece of code in your second Activity/Fragment to get your values.

var args = getArguments()
var index = args.getInt("Key", 0)
Gowtham Subramaniam
  • 3,358
  • 2
  • 19
  • 31
2

simple way to call in java ....like this way

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

}

0
  val otpFragment = OtpFragment()
  val bundle = Bundle()
  bundle.putString("otp", loginDetails[0].otp)
  otpFragment.arguments = bundle
  CommonUtil.changeFragment(otpFragment, R.id.flLogin, Login.manager, R.anim.enter_anim, R.anim.exit_anim)
Yuankun
  • 6,875
  • 3
  • 32
  • 34
0

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))
    }
}
w201
  • 2,018
  • 1
  • 11
  • 15
0

In Kotlin, I can create Fragments and Passing values to another fragment by,

1.First Fragment in which put String.
`

   val storedVerificationId:String = "verificationId"                                                                    
   val fragmentTransaction = fragmentManager?.beginTransaction()
                val bundle = Bundle().apply {
                    putString("storedVerificationId",storedVerificationId) //string and value.
                }

                val fragInfo = otpFragment() //otpFragment is Another Fragment name
                fragInfo.arguments = bundle //bundle in which values stored
                fragmentTransaction!!.replace(R.id.myDrawerlayout,fragInfo) //replace in main activity 
                fragmentTransaction.commit()

`

2.Second Fragment In which getString.

val verificationId = this.arguments?.getString("storedVerificationId")