avatarRanjeet Kumar yadav

Summary

The website content discusses methods for inter-fragment communication in Android applications using Kotlin, specifically through interfaces and ViewModels.

Abstract

In Android development, fragments are essential for creating modular UI components, but communicating between them can be complex. This article outlines two primary methods for fragment communication: using interfaces and using ViewModels. Interfaces establish a communication channel where one fragment can call methods on another, which must implement the interface. On the other hand, ViewModels, part of the Android Architecture Components library, allow fragments to share and manage UI-related data in a lifecycle-aware manner. The article provides code examples for both approaches, highlighting the benefits of ViewModels in avoiding memory leaks and facilitating testing. The choice between interfaces and ViewModels depends on the application's needs, with both methods contributing to a more maintainable and testable codebase.

Opinions

  • The author suggests that using interfaces for fragment communication is a common practice in Android development.
  • ViewModels are recommended for their lifecycle awareness, which helps prevent memory leaks and other issues associated with direct fragment communication.
  • The author implies that ViewModels simplify the testing process of communication between fragments.
  • The article conveys that both interfaces and ViewModels have their own advantages and should be chosen based on the specific requirements of the application.
  • The author emphasizes the importance of understanding these communication methods to design a maintainable and testable codebase.

How to communicate between fragments in Android?

In Android, fragments are a powerful tool for creating reusable and modular UI components. However, when working with multiple fragments in an activity, it can be challenging to communicate between them. In this article, we will explore different ways of communicating between fragments in Android using Kotlin.

Photo by Denny Müller on Unsplash

Communication using Interfaces

One of the most common ways of communicating between fragments in Android is by using interfaces. An interface is a contract that defines a set of methods that a class must implement. By using interfaces, we can create a communication channel between fragments, where one fragment can call a method on the other fragment, and the other fragment can respond by implementing the corresponding method in the interface.

Here is an example of how to use interfaces to communicate between fragments:

interface OnDataChangedListener {
    fun onDataChanged(data: Any)
}

class FragmentA: Fragment() {
    private var listener: OnDataChangedListener? = null

    fun setOnDataChangedListener(listener: OnDataChangedListener?) {
        this.listener = listener
    }

    fun updateData(data: Any) {
        listener?.onDataChanged(data)
    }
}

class FragmentB: Fragment(), OnDataChangedListener {
    override fun onDataChanged(data: Any) {
        // update UI based on data
    }
}

In this example, we have an interface called “OnDataChangedListener” that defines a single method “onDataChanged”. FragmentA has a variable of type OnDataChangedListener which is used to hold a reference to a listener. FragmentB implements this interface and overrides the onDataChanged method. In the activity class, we can call the setOnDataChangedListener method on FragmentA, passing a reference to FragmentB and now FragmentA can call the onDataChanged method on FragmentB.

Communication using ViewModel

Another way of communicating between fragments in Android is by using ViewModels. ViewModels are a part of the Android Architecture Components library, and they are designed to store and manage UI-related data in a lifecycle-aware way. By using ViewModels, we can create a communication channel between fragments, where one fragment can update a shared ViewModel, and the other fragment can observe the changes and update its UI accordingly.

Here is an example of how to use ViewModels to communicate between fragments:

class SharedViewModel: ViewModel() {
    val data = MutableLiveData<Any>()
}
class FragmentA: Fragment() {
    private val sharedViewModel: SharedViewModel by activityViewModels()

    fun updateData(data: Any) {
        sharedViewModel.data.value = data
    }
}

class FragmentB: Fragment() {
    private val sharedViewModel: SharedViewModel by activityViewModels()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        sharedViewModel.data.observe(viewLifecycleOwner, Observer { data ->
            // update UI based on data
        })
    }
}

In this example, we have a SharedViewModel class that holds a MutableLiveData variable called “data”. Both FragmentA and FragmentB have a reference to the same instance of SharedViewModel. FragmentA can update the data by calling updateData method and passing the new data. FragmentB observes the data variable, and when it changes the observer callback is called, where it can update its UI based on the new data.

One of the advantages of using ViewModel is that it allows you to share data between fragments and activities in a lifecycle-aware way. This means that you can avoid memory leaks and other issues that can arise when communicating between fragments directly. Furthermore, ViewModels can be easily tested, which allows you to have a better control over the communication between fragments.

In conclusion, communicating between fragments in Android can be challenging, but by using interfaces or ViewModels, we can create a communication channel between them. Both options have their advantages and disadvantages, and the choice between them will depend on the specific requirements of your application. Understanding these options and how to use them correctly can help you to design a more maintainable and testable codebase.

Thanks for reading.Happy learning 😄

Do support our publication by following it

Also refer to the following articles.

Fragments
Android
Kotlin
Mobile App Development
Blog
Recommended from ReadMedium