0

I am using the standard Android tabs and I need to access my tabs from the parent activity.

I do the following in my MainActivity to get my tabs:

myTab = ((FirstTabFragment)mAdapter.getItem(index));

The problem is that I always get a new object and not the instance because the getItem is implemented as follows:

public class TabsPagerAdapter extends FragmentPagerAdapter {

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

@Override
public Fragment getItem(int index) {

    switch (index) {
        case 0:
            // Status fragment activity
            return new FirstTabFragment();
        case 1:
            // Mission fragment activity
            return new SecondTabFragment();
        case 2:
            // Team fragment activity
            return new ThirdTabFragment();
    }

    return null;
}
...

I googled quite a lot but I still can't find any working solution to get the instance ob my Fragments.

I need the instance because I need to alter the fragment's views and therefore I need it's variables.

Any ideas?

Thanks!

Ron
  • 22,128
  • 31
  • 108
  • 206

2 Answers2

1

The best way is to use the FragmentManager with the method findFragmentById or findFragmentByTag. Of course, you need to declare an ID or a TAG for each fragment created by the FragmentPagerAdapter. If I remember correctly, the default implementation uses the class name as tag.

Thomas Bouron
  • 613
  • 3
  • 11
0

Save the fragment in SparseArray or in HashMap. Add the fragment in array in your getItem method also override the onFragmentDestroy method. In method remove the item from SparseArray or HashMap. Now create a getter method somthing like this

  public Fragment getFragment(int pos) {
               return array.get(pos);

}
Sunny
  • 14,522
  • 15
  • 84
  • 129