Android – Architecture – How to listen child fragment update from parent fragment?

Child fragment

Add listener interface

private var dataChangeListener: DataChangeListener? = null

...

fun setDataChangeListener(dataChangeListener: DataChangeListener) {
        this.dataChangeListener = dataChangeListener
    }

interface DataChangeListener {
    fun onDataChange()
}

Call listener when something occurs

fun updateSomeStuffs() {
    ...
    dataChangeListener?.onDataChange()
    ...
}

Parent fragment

Attach listener to child fragment where it is called

class ParentFragment : BaseFragment(), Contract.View, DataChangeListener {
    ...
    
    override fun onDataChange() {
        // Update parent fragment here
    }

    ...
}

Implement listener

 val childFragment = ChildFragment()
 childFragment.setDataChangeListener(this)

Be the first to comment

Leave a Reply

Your email address will not be published.


*