Sobes.tech
Middle

How can communication between fragments be organized using callbacks?

sobes.tech AI

Answer from AI

Create an interface in a single fragment:

interface MyCallback {
    fun onDataPassed(data: String)
}

Implement this interface in the parent Activity or another fragment/class, which will act as an intermediary:

class MyActivity : AppCompatActivity(), MyCallback {
    override fun onDataPassed(data: String) {
        // Logic to handle data, for example, pass it to another fragment
    }
}

In the first fragment, get a reference to this callback:

class FirstFragment : Fragment() {
    private var callback: MyCallback? = null

    override fun onAttach(context: Context) {
        super.onAttach(context)
        if (context is MyCallback) {
            callback = context
        } else {
            throw RuntimeException("$context must implement MyCallback")
        }
    }

    fun sendData(data: String) {
        callback?.onDataPassed(data)
    }
}

In the code that calls the first fragment, invoke the method to send data:

// ... somewhere in FirstFragment
sendData("Hello from Fragment 1")

The onAttach method guarantees that the parent context implements the required interface, preventing ClassCastException. When using multiple fragments and complex logic, it is preferable to use ViewModel or other architectural components to organize communication.