Mes
Mes

Reputation: 1691

Communication between one Activity and many Fragments through interface

I know there are many similar questions and answers here about this subject, but what I ask is slightly different.

I have four Fragments and each one extend a BaseFragment. I'd like to add a listener to each Fragment so when an event fires to my Activity all the Fragments will get notified about it.

I tried by declaring an interface :

public interface OnClearButtonListener {
     boolean onClearButtonPressed();
}

let my abstract BaseFragment class to implement it :

public abstract class BaseTabsFragment extends android.support.v4.app.Fragment implements OnClearButtonListener{

and I have added the interface in my Activity :

private OnClearButtonListener clearButtonListener;

but now I guess I need to somehow "connect" those two components so when I call from Activity then Fragments will run onClearButtonPressed()

But I'm not sure how I can do it since I use a TabLayout with a ViewPager and the code for the initialization of it is :

private void setUpViewPager(ViewPager viewPager) {
    adapter = new MyTabAdapter(getChildFragmentManager());
    adapter.addFragment(TagsFragment.newInstance(), "TAGS");
    adapter.addFragment(PeopleFragment.newInstance(), "PEOPLE");
    adapter.addFragment(CompaniesFragment.newInstance(), "COMPANIES");
    adapter.addFragment(JobsFragment.newInstance(), "JOBS");
    viewPager.setAdapter(adapter);
    viewPager.setOffscreenPageLimit(3);
}

Upvotes: 0

Views: 118

Answers (2)

mayosk
mayosk

Reputation: 603

Or you can use greenrobot EventBus for that purpose.

First you define a event:

public class OnClearButtonEvent {

    public final String message;

    public OnClearButtonEvent(String message) {
        this.message = message;
    }
}

then in activity :

@Subscribe(threadMode = ThreadMode.MAIN)  
public void onMessageEvent(OnClearButtonEvent event) {/* Do something */};

and in onStart and on Pause you un/register eventbus receivers

and in baseFragment:

EventBus.getDefault().post(new OnClearButtonEvent());

https://github.com/greenrobot/EventBus

If you use RxJava it would be better to use RxEventBus

Upvotes: 2

OneCricketeer
OneCricketeer

Reputation: 191738

In your Activity you hold a list like this

private List<OnClearButtonListener> clearables;

Make each Fragment implement that interface (through a parent class, or otherwise) and as you add to the adapter, you need that same instance added to the list.

BaseFragment f =  TagsFragment.newInstance();
clearables.add(f);
adapter.addFragment(f, "TAGS");
f = PeopleFragment.newInstance();
... 

When you click on the button, loop over that list and call the onClearButtonPressed action

Refer: Observer pattern

Upvotes: 1

Related Questions