Sobes.tech
Junior — Middle

What methods are used for interaction between Fragments in the same Activity?

sobes.tech AI

Answer from AI

Interaction between fragments within the same Activity is usually implemented through the Activity acting as a mediator. Main methods:

  1. Using a callback interface

    • The fragment declares an interface with methods for data transfer.
    • The Activity implements this interface and receives data from one fragment.
    • The Activity passes data to another fragment.
  2. Using ViewModel with Activity lifecycle (Shared ViewModel)

    • A ViewModel is created, associated with the Activity.
    • Both fragments access the same ViewModel.
    • Fragments exchange data via LiveData or other observable objects.
  3. Using FragmentManager to find fragments and call their methods directly

    • Less preferred method, as it increases coupling.

Example with interface:

// In Fragment A
interface OnDataPass {
    fun onDataPass(data: String)
}

class FragmentA : Fragment() {
    lateinit var dataPasser: OnDataPass

    override fun onAttach(context: Context) {
        super.onAttach(context)
        dataPasser = context as OnDataPass
    }

    fun passData() {
        dataPasser.onDataPass("Hello from FragmentA")
    }
}

// In Activity
class MainActivity : AppCompatActivity(), FragmentA.OnDataPass {
    override fun onDataPass(data: String) {
        val fragmentB = supportFragmentManager.findFragmentById(R.id.fragmentB) as FragmentB
        fragmentB.updateData(data)
    }
}