简体   繁体   中英

How to use EventBus in Activity and Fragment on Android

In my application i want use EventBus for call some methods in another activities .
I want when click on backButton in activity ( DetailActivity ), call one method in fragment ( MainFragment ).
in MainFragment i have recyclerView and open this activity ( DetailActivity ) with recyclerView adapter .

I write below codes in DetailActivity and MainFragment but when click on backButton , not call method in MainFragment .

MainFragment codes :

public void onStart() {
    EventBus.getDefault().register(this);
    super.onStart();
}

@Override
public void onStop() {
    super.onStop();
    EventBus.getDefault().unregister(this);
}

@Subscribe(threadMode = ThreadMode.MAIN)
public void onRefreshAuctions(EventUpdateAuctionsState event){
    Toast.makeText(context, "OK", Toast.LENGTH_SHORT).show();
}

DetailActivity codes :

@Override
public void onBackPressed() {
    finishWithAnimate();
    EventBus.getDefault().post(new EventUpdateAuctionsState());
}

EventUpdateAuctionsState codes :

public class EventUpdateAuctionsState {
    public EventUpdateAuctionsState() {
    }
}

Why not call method in MainFragment?
How can i fix it?

Perhaps your Fragment is in stopped state when event is fired. Try to register, unregister in create/destroy lifecycle.

public void onCreate() {
    super.onCreate();
    EventBus.getDefault().register(this);
}

@Override
public void onDestroy() {
    super.onDestroy();
    EventBus.getDefault().unregister(this);
}

Suggestion

By the way why are you using EventBus for just backpress implementation. You can simply do this. If you fragment is child of DetailActivity .

@Override
public void onBackPressed() {
    finishWithAnimate();
    // get your fragment
    if(fragment!=null) fragment.onRefreshAuctions();
}

You can use getFragmentManager().findFragmentByTag("tag") if you don't have fragment instance.

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