简体   繁体   中英

With two fragments on one screen (activity), how can one fragment update the other with EventBus

Ok, so I'm new to android development.

I'm making a recording app. On the same screen as the recording button (to record things) I also have a Fragment to show how many recordings I have. I can tap the recording button to make a recording, but the recording count does not update until the activity's state is refreshed. I want the recording count to update in real time. The fragment is going to be visible in another activity as well, so the logic cannot be in the main recording activity.

I have just integrated EventBus into my project. I have it set up to where the event is a successful recording, and the subscriber is the fragment, so far.

The fragment value correctly gets the event message, but the fragment will not update until it's "refreshed" or rather, goes through its life-cycle of onDestroyView() to onCreateView() .

Please help, I want to be able to update the fragment in real time without having to use the built-in life-cycle functions.

THANKS!

EDIT:

I found a solution by just removing the fragment, then re-adding it.


                supportFragmentManager
                    .beginTransaction()
                    .remove(statsFragmentTwo)
                    .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE)
                    .commit()


                supportFragmentManager
                    .beginTransaction()
                    .add(R.id.main_stats_container_two, statsFragmentTwo)
                    .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
                    .commit()

But still, this doesn't look very efficient! Is there a less costly way?

The fragment value correctly gets the event message, but the fragment will not update until it's "refreshed" or rather, goes through its life cycle of onDestroyView() to onCreateView().

I do not understand the idea of the - " Fragment will not update". If you could listen to the event successfully, you can update the UI elements immediately where you catch the event in your fragment. I am just posing a pseudo code.

if(eventListened) 
    updateUIElementsHere();

You do not have to wait for the lifecycle functions to be called. In your updateUIElementsHere function, you might consider having a similar code that you have in your onCreateView function.

Hope that helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM