Skip to main content

How to pass data between fragments in Kotlin Android

How to pass data between fragments in Kotlin Android.

Here's a detailed step-by-step tutorial on how to pass data between fragments in Kotlin Android:

Step 1: Create Fragments

First, create the fragments that you want to pass data between. Each fragment will have its own layout file and Kotlin class file.

Step 2: Define Interface

Next, define an interface in the fragment that will send the data. This interface will act as a communication channel between the fragments. Create a new Kotlin file and define the interface. For example:

interface DataPassListener {
fun onDataPass(data: String)
}

Step 3: Implement Interface

In the fragment that will send the data, implement the interface. This will allow the fragment to send data to other fragments. For example:

class SenderFragment : Fragment(), DataPassListener {

...

override fun onDataPass(data: String) {
// Handle the data passed from other fragments
}
}

Step 4: Get Reference to Interface

In the fragment that will receive the data, get a reference to the interface. This can be done by casting the activity to the interface type. For example:

class ReceiverFragment : Fragment() {

private lateinit var dataPassListener: DataPassListener

override fun onAttach(context: Context) {
super.onAttach(context)
dataPassListener = context as DataPassListener
}

...
}

Step 5: Pass Data

To pass data from the sender fragment to the receiver fragment, call the interface method and pass the data as a parameter. This can be done in any appropriate event or lifecycle method. For example:

class SenderFragment : Fragment(), DataPassListener {

...

private fun sendData() {
val data = "Hello, Receiver!"
dataPassListener.onDataPass(data)
}
}

Step 6: Handle Data

In the receiver fragment, implement the onDataPass method to handle the data passed from the sender fragment. For example:

class ReceiverFragment : Fragment() {

...

override fun onDataPass(data: String) {
// Handle the data passed from the sender fragment
}
}

Step 7: Fragment Transaction

To display the fragments and enable data passing, use a FragmentTransaction. This can be done in the activity that contains the fragments. For example:

class MainActivity : AppCompatActivity() {

...

private fun displayFragments() {
val senderFragment = SenderFragment()
val receiverFragment = ReceiverFragment()

supportFragmentManager.beginTransaction()
.add(R.id.container, senderFragment)
.add(R.id.container, receiverFragment)
.commit()
}
}

That's it! You have successfully passed data between fragments in Kotlin Android. Remember to replace R.id.container with the appropriate ID of the container view in your activity's layout file.

You can use this approach to pass any type of data between fragments in your Android application.