I looked at all the questions and answers about this. But I could not find the answers to my question.
I have the Fragment
: MyFragment
. In it button
and textView
. I want to that When I will click on the button it will open MyActivity
with two buttons: cancelButton
and saveButton
. When I will click cancelButton
or saveButton
finishes this Activity
and textView
in MyFragment
will change to that what I send in MyActivity
, for example "Cancel Clicked" or "Save Clicked".
What I did:
In MyFragment
:
@Override
public void onResume() {
super.onResume();
EventBus.getDefault().register(this);
}
@Override
public void onPause() {
super.onPause();
EventBus.getDefault().unregister(this);
}
@Subscribe
public void onSaveEvent(Message message) {
textView.setText(message.getMessage());
};
@Subscribe
public void onCancelEvent(Message message) {
textView.setText(message.getMessage());
};
In MyActivity
:
@OnClick(R.id.saveBtn)
public void saveClick(){
finish();
EventBus.getDefault().postSticky(new Message("Save clicked!"));
}
@OnClick(R.id.cancelBtn)
public void cancelClick(){
finish();
EventBus.getDefault().postSticky(new Message("Cancel Clicked"));
}
But it does not work I think it because when I start MyActivity
, Event Bus
unregisters in onPause()
therefor can`t receive event
I tried with interfaces and it worked. But I want to realize it with EventBus
How can I do on Event Bus
?
You can solve this with a StickyEvents .
In Fragment
@Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
public void onEvent(Message message) {
Message stickyEvent = EventBus.getDefault().getStickyEvent(Message.class);
if(stickyEvent != null) {
tv.setText(message.getMessage());
EventBus.getDefault().removeStickyEvent(stickyEvent);
}
};
According to this , you should register and unregister in onStart and onStop.
I think you should post events before calling finish() in your activity.
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.