Pass parameters from activity to fragment using kotlin

Hello Guys, While using fragments in android most of the time we have to pass some parameters from activity to fragment. We are very much aware of this functionality in android using java but what about kotlin. How can we achieve this functionality in kotlin.

  • Here i'm going to explain you how to send value as a parameter in activity to fragment in kotlin. 

1) Your main activity where you bind your fragment :


 val testData = TestData()
 testData.name = "test data 1"
 testData.value = 1

 val kotlinFragment = KotlinFragment.newInstance("Hello", 111, testData)

                    supportFragmentManager
                            .beginTransaction()
                            .replace(R.id.content, kotlinFragment, fragment.KotlinFragment.javaClass.name)
                            .commit()

2) Your Fragment where you will get parameters in newInstance() method


class KotlinFragment : Fragment() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val name = arguments.getString("name")
        val value = arguments.getInt("value")
        val testData = arguments.getSerializable("testData") as TestData
    }

    companion object {

        fun newInstance(name: String, value: Int, testData: TestData): KotlinFragment {

            val args = Bundle()
            args.putString("name", name)
            args.putInt("value", value)
            args.putSerializable("testData", testData)
            val fragment = KotlinFragment()
            fragment.arguments = args
            return fragment
        }
    }
}

Hope, You get this helpful. Good Luck ;)

Comments