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(
            this,
            R.drawable.ic_baseline_menu_24
        )
        binding.bottomAppBar.menu.findItem(R.id.filter).isVisible = false
        binding.bottomSheetTestata.titleBottomSheet.text = "Modifica Documento"
        bottomSheetTestataBehavior.state = BottomSheetBehavior.STATE_COLLAPSED
        binding.bottomAppBar.menu.findItem(R.id.testata).isVisible = tipo != "Etichette"
    }else {
        binding.bottomAppBar.navigationIcon = null
        binding.bottomAppBar.menu?.findItem(R.id.testata)?.isVisible = false
        binding.bottomAppBar.menu?.findItem(R.id.filter)?.isVisible = true
        binding.bottomSheetTestata.titleBottomSheet.text = "Nuovo Documento"
        clearTestata()
        bottomSheetBehavior.state = BottomSheetBehavior.STATE_COLLAPSED
    }
}

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

Answer

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

https://greenrobot.org/eventbus/

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 */ }