Communicate Between Fragment-Activity (CBFA)

In many cases, we often find ourselves trying to communicate between an activity and a fragment, either to pass data back to the activity or to notify the activity that an event occurred in the hosted fragment. Here are three ways to accomplish this, or at least three ways that I have tried during my career as an Android developer. All three have a similar goal, which is to communicate between the two components.


Interface Communication (Communication Through Interface):

  • Define an interface that contains the methods that the activity or fragment will implement.
  • The activity implements the interface, and the fragment calls methods on the interface to send data or notify the activity about an event.
interface FragmentCallback {
  fun  onNameAdded (name: String)
}

or without data throw,

interface FragmentCallback {
     fun  onNameAdded ()
}

it all depends on your case study.

Implement your interface into the Activities that need it.

class  MainActivity : AppCompatActivity(), FragmentCallback {
     override  fun  onNameAdded (name: String) {
     // here were you receive the data or event
    }

    override  fun  onCreate (savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

    }
}

Next we go into Fragment to apply this interface.

Callback Methods:

  • Activities can provide callback methods to fragments.
  • Fragments call these methods when they need to send data or notify the activity about certain events.
So, we use polymorphism to get the interface instance implemented by MainActivity. That's it, simple right?

private lateinit var fragmentCallback: FragmentCallback
 override  fun  onAttach (context: Context?) {
super.onAttach(context)
fragmentCallback = context as FragmentCallback
}

Finally, you just call the callback function wherever you want.

saveButton.setOnClickListener {
  if (nameEditText.text.isEmpty())
  return @setOnClickListener
 fragmentCallback.onNameAdded( "Anu Gede" ) //here
 }

ViewModel Communication (Communication Through ViewModel):

  • Use ViewModel architecture to share data between activities and fragments.
  • Activities and fragments can subscribe to the same ViewModel, and they can communicate by sharing data through that ViewModel.
  • It is important to choose a method that suits the needs of the project and the developer's preferences. Each approach has its own advantages and disadvantages. It all depends on the complexity of the application and how data or events need to be exchanged between activities and fragments.
Even other references mention 3 ways such as:

  1. Interface
  2. Instance Method
  3. Bus events
  4. Broadcast
But of all those ways, for small scopes it is more efficient to use Interface or ViewModel.

Post a Comment

Previous Next

نموذج الاتصال