Skip to content

How can i listen for Fragment change in my Activity?

I have an Activity which based on intent opens Fragment1 or Fragment2.

From the activity after some stuff are done if the user is in Fragment1 i replace the fragment to Fragment2 and that can be done even from the Fragment1 diretly.

For each Fragment i have to change items in my BottomAppBar, till i’m in Activity i have no problems with it as i’ve made just a function which changes the bottomAppBar items based on value passed it in.

The issue is when the .replace is called directly from the fragment.

So i tought if it was possible to set in anyway a ‘FragmentListener’ which listens for fragment change in my Activity and call that function from it..

My function looks like this:

private fun changeBottomBar(corpo: Boolean = false) {
    if (corpo) {
        binding.bottomAppBar.navigationIcon = ContextCompat.getDrawable(
        ) = false
        binding.bottomSheetTestata.titleBottomSheet.text = "Modifica Documento"
        bottomSheetTestataBehavior.state = BottomSheetBehavior.STATE_COLLAPSED = tipo != "Etichette"
    }else {
        binding.bottomAppBar.navigationIcon = null = false = true
        binding.bottomSheetTestata.titleBottomSheet.text = "Nuovo Documento"
        bottomSheetBehavior.state = BottomSheetBehavior.STATE_COLLAPSED

And i call it for every .replace where if the Fragment is Fragment2 i pass to it corpo = true


You can use EventBus Open source library for subscribing and publishing events.

For Publishing Event

 //In fragment
 EventBus.getDefault().post(new MessageEvent());

For Subscribing Event in Activity

//In Activity
@Subscribe(threadMode = ThreadMode.MAIN)  
public void onMessageEvent(MessageEvent event) {/* Do something */};

Define you custom model class for event

public static class MessageEvent { /* Additional fields if needed */ }