How to hide FAB from subfragment?

Viewed 26

Well, i have an Activity(with ViewPager and FAB)

In ViewPager there is a NotesFragment(fragment contains only RecyclerView)

And I have a Fragment calls AddNoteFragment which do the job of Adding and Showing existing Note: 1) From Activity fab opens AddNoteFragment to add note, which is logical, 2) And from RecyclerView, clicking item opens AddNoteFragment with details of clicked item

Question: how to hide FAB on Activity, when i'm opening AddNoteFragment to show exciting note correctly? The only way I know is a using interface and transfering it up, but this will look like RecyclerViewAdapter -> NotesFragment -> ViewPagerAdapter -> Activity, it looks weird..

1 Answers

While I think using interface it's a good way to do it, you might want to take a look at EventBus (https://github.com/greenrobot/EventBus), it works similary as BroadcastReceiver, all you have to do is to wait for the event on your Activity, and hide/show it whenever you want. Below is the code you have to put on your activity:

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

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

@Subscribe(threadMode = ThreadMode.MAIN)  
public void onMessageEvent(Boolean show) {if (show){
  fab.show()
}else{
  fab.hide()
}};

then, whenever you want, you just have to call this

EventBus.getDefault().post(/* true or false*/);
Related