How to get existing fragments when using FragmentPagerAdapter
Asked Answered
A

14

112

I have problem making my fragments communicating with each other through the Activity, which is using the FragmentPagerAdapter, as a helper class that implements the management of tabs and all details of connecting a ViewPager with associated TabHost. I have implemented FragmentPagerAdapter just as same as it is provided by the Android sample project Support4Demos.

The main question is how can I get particular fragment from FragmentManager when I don't have neither Id or Tag? FragmentPagerAdapter is creating the fragments and auto generating the Id and Tags.

Ajmer answered 26/12, 2012 at 1:7 Comment(2)
Possible duplicate of Getting the current Fragment instance in the viewpagerGaillardia
Most of the answers here don't work in production, so check my answer in https://mcmap.net/q/57532/-how-to-get-elements-of-fragments-created-by-viewpager-in-mainactivityNorling
V
209

Summary of the problem

Note: In this answer I'm going to reference FragmentPagerAdapter and its source code. But the general solution should also apply to FragmentStatePagerAdapter.

If you're reading this you probably already know that FragmentPagerAdapter/FragmentStatePagerAdapter is meant to create Fragments for your ViewPager, but upon Activity recreation (whether from a device rotation or the system killing your App to regain memory) these Fragments won't be created again, but instead their instances retrieved from the FragmentManager. Now say your Activity needs to get a reference to these Fragments to do work on them. You don't have an id or tag for these created Fragments because FragmentPagerAdapter set them internally. So the problem is how to get a reference to them without that information...

Problem with current solutions: relying on internal code

A lot of the solutions I've seen on this and similar questions rely on getting a reference to the existing Fragment by calling FragmentManager.findFragmentByTag() and mimicking the internally created tag: "android:switcher:" + viewId + ":" + id. The problem with this is that you're relying on internal source code, which as we all know is not guaranteed to remain the same forever. The Android engineers at Google could easily decide to change the tag structure which would break your code leaving you unable to find a reference to the existing Fragments.

Alternate solution without relying on internal tag

Here's a simple example of how to get a reference to the Fragments returned by FragmentPagerAdapter that doesn't rely on the internal tags set on the Fragments. The key is to override instantiateItem() and save references in there instead of in getItem().

public class SomeActivity extends Activity {
    private FragmentA m1stFragment;
    private FragmentB m2ndFragment;

    // other code in your Activity...

    private class CustomPagerAdapter extends FragmentPagerAdapter {
        // other code in your custom FragmentPagerAdapter...

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

        @Override
        public Fragment getItem(int position) {
            // Do NOT try to save references to the Fragments in getItem(),
            // because getItem() is not always called. If the Fragment
            // was already created then it will be retrieved from the FragmentManger
            // and not here (i.e. getItem() won't be called again).
            switch (position) {
                case 0:
                    return new FragmentA();
                case 1:
                    return new FragmentB();
                default:
                    // This should never happen. Always account for each position above
                    return null;
            }
        }

        // Here we can finally safely save a reference to the created
        // Fragment, no matter where it came from (either getItem() or
        // FragmentManger). Simply save the returned Fragment from
        // super.instantiateItem() into an appropriate reference depending
        // on the ViewPager position.
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            Fragment createdFragment = (Fragment) super.instantiateItem(container, position);
            // save the appropriate reference depending on position
            switch (position) {
                case 0:
                    m1stFragment = (FragmentA) createdFragment;
                    break;
                case 1:
                    m2ndFragment = (FragmentB) createdFragment;
                    break;
            }
            return createdFragment;
        }
    }

    public void someMethod() {
        // do work on the referenced Fragments, but first check if they
        // even exist yet, otherwise you'll get an NPE.

        if (m1stFragment != null) {
            // m1stFragment.doWork();
        }

        if (m2ndFragment != null) {
            // m2ndFragment.doSomeWorkToo();
        }
    }
}

or if you prefer to work with tags instead of class member variables/references to the Fragments you can also grab the tags set by FragmentPagerAdapter in the same manner: NOTE: this doesn't apply to FragmentStatePagerAdapter since it doesn't set tags when creating its Fragments.

@Override
public Object instantiateItem(ViewGroup container, int position) {
    Fragment createdFragment = (Fragment) super.instantiateItem(container, position);
    // get the tags set by FragmentPagerAdapter
    switch (position) {
        case 0:
            String firstTag = createdFragment.getTag();
            break;
        case 1:
            String secondTag = createdFragment.getTag();
            break;
    }
    // ... save the tags somewhere so you can reference them later
    return createdFragment;
}

Note that this method does NOT rely on mimicking the internal tag set by FragmentPagerAdapter and instead uses proper APIs for retrieving them. This way even if the tag changes in future versions of the SupportLibrary you'll still be safe.


Don't forget that depending on the design of your Activity, the Fragments you're trying to work on may or may not exist yet, so you have to account for that by doing null checks before using your references.

Also, if instead you're working with FragmentStatePagerAdapter, then you don't want to keep hard references to your Fragments because you might have many of them and hard references would unnecessarily keep them in memory. Instead save the Fragment references in WeakReference variables instead of standard ones. Like this:

WeakReference<Fragment> m1stFragment = new WeakReference<Fragment>(createdFragment);
// ...and access them like so
Fragment firstFragment = m1stFragment.get();
if (firstFragment != null) {
    // reference hasn't been cleared yet; do work...
}
Veronicaveronika answered 26/3, 2015 at 1:23 Comment(8)
This is a really good solution, but it seems to lose its effectiveness if you don't know how many fragments will be passed in.Revivalism
@Zorpix you can store the create fragments in a HashMap: map.put(position, createdFragment);Murrain
This works great with the tags, but not the other way. I also had to check for null reference in the instantiateitem method and return new Fragment() if null is true. But nice example. helped alotStepsister
no need to override anything and you actually shouldn't be overriding instantiateItem. the proper way to do this is to call instantiateItem in onCreate method of your activity surrounded by startUpdate and finishUpdate. See my answer for detailsPopular
@Tony Chan How to use viewPagerAdapter ? If activity is recreated, we have to create new instance of viewPagerAdapter and ViewPager, how this instantiateItem() will help ? If adapter is newly created, then everything is new. Please help with some code in answer ?Apparition
yeah, cheers. was getting null references to my fragments in the adapter. was wondering what was going on. alas, i was omnly adding to my list of references in getItem(). so i have old references. cheers!Compliance
When using FragmentStatePagerAdapter this is an incomplete answer. I recommend looking at the source code for it at android.googlesource.com/platform/frameworks/support/+/…Mello
Great solution. We used a weakreferences Map to save the references to fragments. Something like Map<Integer, WeakReference<Fragment>> created_fragments_references;Outlook
A
84

I have found answer on my question based on following post: reusing fragments in a fragmentpageradapter

Few things I have learned:

  1. getItem(int position) in the FragmentPagerAdapter is rather misleading name of what this method actually does. It creates new fragments, not returning existing ones. In so meaning, the method should be renamed to something like createItem(int position) in the Android SDK. So this method does not help us getting fragments.
  2. Based on explanation in the post support FragmentPagerAdapterholds reference to old fragments you should leave the creation of the fragments to the FragmentPagerAdapter and in so meaning you have no reference to the Fragments or their tags. If you have fragment tag though, you can easily retrieve reference to it from the FragmentManager by calling findFragmentByTag(). We need a way to find out tag of a fragment at given page position.

Solution

Add following helper method in your class to retrieve fragment tag and send it to the findFragmentByTag() method.

private String getFragmentTag(int viewPagerId, int fragmentPosition)
{
     return "android:switcher:" + viewPagerId + ":" + fragmentPosition;
}

NOTE! This is identical method that FragmentPagerAdapter use when creating new fragments. See this link http://code.google.com/p/openintents/source/browse/trunk/compatibility/AndroidSupportV2/src/android/support/v2/app/FragmentPagerAdapter.java#104

Ajmer answered 26/12, 2012 at 10:40 Comment(6)
Btw, there is more about the topic in this Q&A: #6976527Rezzani
what is the viewId input parameter? Which view?Dealings
@Dealings viewId is the id of the ViewPager.Edmonson
Maybe instead of guessing the tag the fragment could tell its tag to its activity in onAttach()?Concierge
no need to recreate fragment tags and rely on compatibility with the internal code: you can (and actually you should) call instantiateItem in onCreate method of your activity surrounded by startUpdate and finishUpdate to get references to your fragments (fragments are cached in FragmentManager, so no need to worry that you would create unnecessary instances). See my answer for details.Popular
Above Solutions is correct way to solve this problem. Note you have to set the setOffscreenPageLimit() if using FragmentStatePagerAdapter. Simpler way to use findFragmentByTag() can be found at linkFruitless
P
17

you don't need to override instantiateItem nor rely on compatibility with internal makeFragmentName method by manually creating fragment tags .
instantiateItem is a public method so you can call it in onCreate method of your activity surrounded with calls to startUpdate and finishUpdate methods as described in PagerAdapter javadoc:

A call to the PagerAdapter method startUpdate(ViewGroup) indicates that the contents of the ViewPager are about to change. One or more calls to instantiateItem(ViewGroup, int) and/or destroyItem(ViewGroup, int, Object) will follow, and the end of an update will be signaled by a call to finishUpdate(ViewGroup).

You can then by the way of the above, store references to instances of your fragments on local vars if you need. See example:

public class MyActivity extends AppCompatActivity {

    Fragment0 tab0; Fragment1 tab1;

    @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.myLayout);
        ViewPager viewPager = (ViewPager) findViewById(R.id.myViewPager);
        MyPagerAdapter adapter = new MyPagerAdapter(getSupportFragmentManager());
        viewPager.setAdapter(adapter);
        ((TabLayout) findViewById(R.id.tabs)).setupWithViewPager(viewPager);

        adapter.startUpdate(viewPager);
        tab0 = (Fragment0) adapter.instantiateItem(viewPager, 0);
        tab1 = (Fragment1) adapter.instantiateItem(viewPager, 1);
        adapter.finishUpdate(viewPager);
    }

    class MyPagerAdapter extends FragmentPagerAdapter {

        public MyPagerAdapter(FragmentManager manager) {super(manager);}

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

        @Override public Fragment getItem(int position) {
            if (position == 0) return new Fragment0();
            if (position == 1) return new Fragment1();
            return null;  // or throw some exception
        }

        @Override public CharSequence getPageTitle(int position) {
            if (position == 0) return getString(R.string.tab0);
            if (position == 1) return getString(R.string.tab1);
            return null;  // or throw some exception
        }
    }
}

instantiateItem will first try to get references to existing fragment instances from FragmentManager. Only if they don't exist yet, it will create new ones using getItem method from your adapter and "store" them in the FragmentManager for any future use.

UPDATE 05/2022: according to this comment the below part may lead to suboptimal performance in the current implementation.

Following the above javadoc, you still should call instantiateItem for all your tabs surrounded by startUpdate/finishUpdate in your onCreate method even if you don't need to obtain references to your fragments:

    adapter.startUpdate(viewPager);
    // ignoring return values of the below 2 calls, just side effects matter:
    adapter.instantiateItem(viewPager, 0);
    adapter.instantiateItem(viewPager, 1);
    adapter.finishUpdate(viewPager);

If you don't do so, then you are risking that your fragment instances will never be committed to FragmentManager : when your activity becomes foreground instantiateItem will be called automatically to obtain your fragments, but startUpdate/finishUpdate may not (depending on implementation details) and what they basically do is begin/commit a FragmentTransaction.
This may result in references to the created fragment instances being lost very quickly (for example when you rotate your screen) and recreated much more often than necessary. Depending on how "heavy" your fragments are, it may have a non-negligible performance consequences.
Moreover, in such case instances of fragments stored on local vars may become stale: if android platform tries to obtain them from FragmentManager for whatever reason, it will fail and thus will create and use new ones, while your vars will still be referencing the old ones.

Popular answered 27/12, 2016 at 12:31 Comment(7)
It might be the best solution in some cases. But what will happen if FragmentManger will kill the fragment and recrate it?Xylem
@Xylem FragmentManager can't just randomly kill (destroy is the right word here) your Fragment (think what would happen if it decided to kill a Fragment that is currently being displayed ;) ). Generally lifecycle of a Fragment is bound to its Activity (see github.com/xxv/android-lifecycle for details) -> a Fragment can only be destroyed if its Activity was destroyed. In such case when a user navigates back to the given Activity its onCreate will be called again and a new instance of the Fragment will be created.Popular
Should you really create fragments rather than rely on them being created as an user scrolls ViewPager for example?Wept
@Wept yes, you really should. The docs excerpt I provided clearly states it and "Some additional info" section explains why.Popular
I don't think this is the right answer. Yes, it achieves the goal of instantiating all fragments properly and keeping them that way, but with a major overhead. Each fragment returned from this manual call of instantiateItem receives onAttach, onCreate and onCreateView, even though the view is not needed. Only when you start swiping back and forth the view pager, the unneeded fragments will start receiving onDestroyView, and finally only three fragments will be left with their views created (the current, the one to the left and the one to the right), like it's supposed to be in a viewpager.Justificatory
The entire principle of calling instantiateItem manually goes against the efforts of FragmentPagerAdapter and FragmentStatePagerAdapter to conserve resources. And if the former will keep once instantiated fragments alive (but will be destroying and recreating their views as needed), the latter will be actually killing the fragments when they are not immediately required, in which case this manual creation is extra unhelpful.Justificatory
@Justificatory thanks for your input! I still think this is the right way if you need to store references to your fragments. However, you probably have a point that calling instantiateItem should be avoided when there's no need to store references. I don't do Android development these days, so can't check it myself easily, but I've added a note based on your comment.Popular
P
13

The way I did it is define an Hashtable of WeakReferences as follows:

protected Hashtable<Integer, WeakReference<Fragment>> fragmentReferences;

Then I wrote the getItem() method like this:

@Override
public Fragment getItem(int position) {

    Fragment fragment;
    switch(position) {
    case 0:
        fragment = new MyFirstFragmentClass();
        break;

    default:
        fragment = new MyOtherFragmentClass();
        break;
    }

    fragmentReferences.put(position, new WeakReference<Fragment>(fragment));

    return fragment;
}

Then you can write a method:

public Fragment getFragment(int fragmentId) {
    WeakReference<Fragment> ref = fragmentReferences.get(fragmentId);
    return ref == null ? null : ref.get();
}

This seems to work well and I find it a little less hacky than the

"android:switcher:" + viewId + ":" + position

trick, as it does not rely on how the FragmentPagerAdapter is implemented. Of course if the fragment has been released by the FragmentPagerAdapter or if it has not been yet created, getFragment will return null.

If anybody finds something wrong with this approach, comments are more than welcome.

Pinball answered 24/5, 2014 at 10:10 Comment(4)
int fragmentId should be renamed to int positionPneumogastric
I was using a very similar approach. But this fails when the pager is created from a savedState bundle. eg: Activity goes into background and comes back to foreground after the onSavedStateInstance() is called. In that case the getItem() methods won't be called.Longdrawnout
also, the fact that a fragment has been destroyed, does not guarantee that there are no strong references to it (although it's likely, but NOT guaranteed) in which case your map would still contain stale fragments.Popular
This will not work correctly after the system recreates the Fragments.Norling
B
10

I created this method which is working for me to get a reference to the current fragment.

public static Fragment getCurrentFragment(ViewPager pager, FragmentPagerAdapter adapter) {
    try {
        Method m = adapter.getClass().getSuperclass().getDeclaredMethod("makeFragmentName", int.class, long.class);
        Field f = adapter.getClass().getSuperclass().getDeclaredField("mFragmentManager");
        f.setAccessible(true);
        FragmentManager fm = (FragmentManager) f.get(adapter);
        m.setAccessible(true);
        String tag = null;
        tag = (String) m.invoke(null, pager.getId(), (long) pager.getCurrentItem());
        return fm.findFragmentByTag(tag);
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } 
    return null;
}
Blob answered 14/3, 2013 at 11:31 Comment(1)
Nice just to remember creating the Method and Field outside the method for better performanceRecognizance
T
10

FragmentStateAdapter for ViewPager2 UPDATE

FragmentStateAdapter has createFragment() instead of getItem(). And there is no such method as instantiateView().

So when the hosting Activity/Fragment is recreated after the configuration change, createFragment() doesn't get called. This means that fragments in the adapter are not created again, but instead their instances are retrieved from FragmentManager. So if you need to do some work on the fragments, you can simply get them from FragmentManager.

Adapter creation:

CustomFragmentAdapter adapter = new CustomFragmentAdapter(getChildFragmentManager(), getLifecycle());

Retrieving fragments from FragmentManager after Activity/Fragment reload:

    FragmentManager manager = getChildFragmentManager();
    ArrayList<Fragment> fragments = new ArrayList<>(manager.getFragments());

    for (Fragment fr : fragments) {
        
        // do something
    }
Technetium answered 20/6, 2021 at 16:11 Comment(0)
C
2

the solution suggested by @personne3000 is nice, but it has one problem: when activity goes to the background and gets killed by the system (in order to get some free memory) and then restored, the fragmentReferences will be empty, because getItem wouldn't be called.

The class below handles such situation:

public abstract class AbstractHolderFragmentPagerAdapter<F extends Fragment> extends FragmentPagerAdapter {

    public static final String FRAGMENT_SAVE_PREFIX = "holder";
    private final FragmentManager fragmentManager; // we need to store fragment manager ourselves, because parent's field is private and has no getters.

    public AbstractHolderFragmentPagerAdapter(FragmentManager fm) {
        super(fm);
        fragmentManager = fm;
    }

    private SparseArray<WeakReference<F>> holder = new SparseArray<WeakReference<F>>();

    protected void holdFragment(F fragment) {
        holdFragment(holder.size(), fragment);
    }

    protected void holdFragment(int position, F fragment) {
        if (fragment != null)
            holder.put(position, new WeakReference<F>(fragment));
    }

    public F getHoldedItem(int position) {
        WeakReference<F> ref = holder.get(position);
        return ref == null ? null : ref.get();
    }

    public int getHolderCount() {
        return holder.size();
    }

    @Override
    public void restoreState(Parcelable state, ClassLoader loader) { // code inspired by Google's FragmentStatePagerAdapter implementation
        super.restoreState(state, loader);
        Bundle bundle = (Bundle) state;
        for (String key : bundle.keySet()) {
            if (key.startsWith(FRAGMENT_SAVE_PREFIX)) {
                int index = Integer.parseInt(key.substring(FRAGMENT_SAVE_PREFIX.length()));
                Fragment f = fragmentManager.getFragment(bundle, key);
                holdFragment(index, (F) f);
            }
        }
    }

    @Override
    public Parcelable saveState() {
        Bundle state = (Bundle) super.saveState();
        if (state == null)
            state = new Bundle();

        for (int i = 0; i < holder.size(); i++) {
            int id = holder.keyAt(i);
            final F f = getHoldedItem(i);
            String key = FRAGMENT_SAVE_PREFIX + id;
            fragmentManager.putFragment(state, key, f);
        }
        return state;
    }
}
Cavafy answered 27/8, 2014 at 8:34 Comment(0)
C
2

The main road block with getting a handle to the fragments is you can not rely on getItem(). After an orientation change, references to the fragments will be null and getItem() is not called again.

Here's an approach that does not rely upon the implementation of FragmentPagerAdapter to get the tag. Override instantiateItem() which will return the fragment created from getItem() or found from the fragment manager.

@Override
public Object instantiateItem(ViewGroup container, int position) {
    Object value =  super.instantiateItem(container, position);

    if (position == 0) {
        someFragment = (SomeFragment) value;
    } else if (position == 1) {
        anotherFragment = (AnotherFragment) value;
    }

    return value;
}
Crescentic answered 22/6, 2015 at 20:16 Comment(0)
L
0

See this post on returning fragments from the FragmentPagerAdapter. Does rely on you knowing the index of your fragment - but this would be set in getItem() (at instantiation only)

Lamentable answered 22/1, 2013 at 20:22 Comment(0)
S
0

I managed to solve this issue by using ids instead of tags. (I am using I defined FragmentStatePagerAdapter which uses my custom Fragments in which I overrode the onAttach method, where you save the id somewhere:

@Override
public void onAttach(Context context){
    super.onAttach(context);
    MainActivity.fragId = getId();
}

And then you just access the fragment easily inside the activity:

Fragment f = getSupportFragmentManager.findFragmentById(fragId);
Severen answered 3/10, 2015 at 15:1 Comment(0)
C
0

I don't know if this is the best approach but nothing else worked for me. All other options including getActiveFragment returned null or caused the app to crash.

I noticed that on screen rotation the fragment was being attached so I used it to send the fragment back to the activity.

In the fragment:

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        mListener = (OnListInteractionListener) activity;
        mListener.setListFrag(this);
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

Then in the activity:

@Override
public void setListFrag(MyListFragment lf) {
    if (mListFragment == null) {
        mListFragment = lf;
    }
}

And finally in activity onCreate():

if (savedInstanceState != null) {
    if (mListFragment != null)
        mListFragment.setListItems(items);
}

This approach attaches the actual visible fragment to the activity without creating a new one.

Chaschase answered 17/2, 2017 at 16:54 Comment(0)
C
0

Not sure if my method was the correct or best way to do this since I am a relative beginner with Java/Android, but it did work (I'm sure it violates object oriented principles but no other solution worked for my use case).

I had a hosting Activity that was using a ViewPager with a FragmentStatePagerAdapter. In order to get references to the Fragments that were created by FragmentStatePagerAdapter I created a callback interface within the fragment class:

public interface Callbacks {
    public void addFragment (Fragment fragment);
    public void removeFragment (Fragment fragment);
}

In the hosting activity I implemented the interface and created a LinkedHasSet to keep track of the fragments:

public class HostingActivity extends AppCompatActivity implements ViewPagerFragment.Callbacks {

    private LinkedHashSet<Fragment> mFragments = new LinkedHashSet<>();

    @Override
    public void addFragment (Fragment fragment) {
        mFragments.add(fragment);
    }

    @Override
    public void removeFragment (Fragment fragment) {
        mFragments.remove(fragment);
    }
}

Within the ViewPagerFragment class I added the fragments to the list within onAttach and removed them within onDetach:

public class ViewPagerFragment extends Fragment {

    private Callbacks mCallbacks;

    public interface Callbacks {
        public void addFragment (Fragment fragment);
        public void removeFragment (Fragment fragment);
    } 

    @Override
    public void onAttach (Context context) {
        super.onAttach(context);
        mCallbacks = (Callbacks) context;
        // Add this fragment to the HashSet in the hosting activity
        mCallbacks.addFragment(this);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        // Remove this fragment from the HashSet in the hosting activity
        mCallbacks.removeFragment(this);
        mCallbacks = null;
    }
}

Within the hosting activity you'll now be able to use mFragments to iterate through the fragments that currently exist in the FragmentStatePagerAdapter.

Clamatorial answered 21/5, 2018 at 1:19 Comment(0)
I
0

This class do the trick without relying on internal tags. Warning: Fragments should be accessed using the getFragment method and not the getItem one.

public class ViewPagerAdapter extends FragmentPagerAdapter {

    private final Map<Integer, Reference<Fragment>> fragments = new HashMap<>();
    private final List<Callable0<Fragment>> initializers = new ArrayList<>();
    private final List<String> titles = new ArrayList<>();

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

    void addFragment(Callable0<Fragment> initializer, String title) {
        initializers.add(initializer);
        titles.add(title);
    }

    public Optional<Fragment> getFragment(int position) {
        return Optional.ofNullable(fragments.get(position).get());
    }

    @Override
    public Fragment getItem(int position) {
        Fragment fragment =  initializers.get(position).execute();
        return fragment;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        Fragment fragment = (Fragment) super.instantiateItem(container, position);
        fragments.put(position, new WeakReference<>(fragment));
        return fragment;
    }

    @Override
    public int getCount() {
        return initializers.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return titles.get(position);
    }
}
Ibis answered 30/8, 2018 at 11:58 Comment(0)
P
-7

Just go on try this code,

public class MYFragmentPAdp extends FragmentPagerAdapter {

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

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

     @Override
     public Fragment getItem(int position) {
         if (position == 0)
             Fragment fragment = new Fragment1();
         else (position == 1)
             Fragment fragment = new Fragment2();
         return fragment;
     }
}
Purim answered 26/12, 2012 at 11:3 Comment(4)
Najib, like i explained in my answer below getItem()is creating new fragment in stead of returning existing ones as one could expect given name get and not create. See my solution in the same post.Ajmer
Fragment fragment = new YourCustomFragmentClass(); write here check for this.Purim
I still dont understand how this change the fact that you are creating new fragment in stead of getting existing one..Ajmer
You still initialize and return for your custom fragment only,like as Fragment fragment = new YourFragment(); return fragment;Purim

© 2022 - 2024 — McMap. All rights reserved.