Call Tabbed Fragment method from Activity

user2029541 picture user2029541 · Apr 12, 2015 · Viewed 13.2k times · Source

I have one activity that comprises of three fragments. The fragments use the actionbar tabs using a PagerAdapter. What I want to do is access a method in the active tabbed fragment from the main activity. I have tried the below code but this just returns the fragment as null, so I guess it cant find it within the tabs!

 NPListFragment articleFrag = (NPListFragment) getSupportFragmentManager().findFragmentByTag("NP");
    articleFrag.refreshT();

PagerAdapter:

public class AppSectionsPagerAdapter extends FragmentPagerAdapter {
public AppSectionsPagerAdapter(FragmentManager fm) {
    super(fm);
}

@Override
public Fragment getItem(int i) {
    switch (i) {
        case 0:
            return new NPListFragment();
        case 1:
            return new PListFragment();
        case 2:
            return new FavouritesFragment();
    }
    return null;
}

@Override
public int getCount() {
    return 3;
}

} Can anyone advise? I have spent about 6 hours on this, i'm just not making any progress resolving this.

Answer

Stephane Mathis picture Stephane Mathis · Apr 12, 2015

What you should do is : create only once each fragment and then give it for all calls to the getItem method.

For instance :

public class AppSectionsPagerAdapter extends FragmentPagerAdapter {

Fragment one, two, three;

public AppSectionsPagerAdapter(FragmentManager fm) {
    super(fm);
}

@Override
public Fragment getItem(int i) {
    switch (i) {
        case 0:
            if(one == null)
                one = new NPListFragment();
            return one;
        case 1:
            if(two == null)
                two= new PListFragment();
            return two;
        case 2:
            if(three == null)
                three= new FavouritesFragment();
            return three;
    }
    return null;
}

@Override
public int getCount() {
    return 3;
}

} 

Now, even you in your activity you can call getItem

You'll just need to cast it to the real fragment class if you want to call a specific method.

int pos = viewpager.getCurrentItem();    
Fragment activeFragment = adapter.getItem(pos);
if(pos == 0)
    ((NPListFragment)activeFragment).refreshT();
...