Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't change tag of fragment

I have a few pages (fragments) in a viewPager.
When I tried to remove (for instance) the first one, like this:

mFragmentManager.beginTransaction().remove(Page1).commit();

It says that

IllegalStateException has occured.

I don't know why. Could anybody help me? thanks.

Exception:

java.lang.IllegalStateException: Can't change tag of fragment Page2{40586418 #2 id=0x7f080006 android:switcher:2131230726:2}: was android:switcher:2131230726:2 now android:switcher:2131230726:1
like image 792
Daniel Dubec Avatar asked Nov 05 '22 04:11

Daniel Dubec


1 Answers

This is an old question, but anyhow here is some information in the hope that it will help someone.

ViewPager works together with its adapter which is set to it via ViewPager#setAdapter(). In the case of this question, it seems FragmentPagerAdapter is used as an adapter (since this adapter names the fragments android:switcher:[x]:[y] as appears in the exception).

One important observation about the FragmentPagerAdapter is this:

FragmentPagerAdapter owns the allocated fragments that are used in the ViewPager.

The user of ViewPager with conjunction of ViewPagerAdapter has to define a subclass of FragmentPagerAdapter implementing the getItem() method, prototyped as follows:

public abstract Fragment getItem(int position);

This function creates the different fragments used by the ViewPager as pages. The implementation of this method should be looked as a service provided by the subclass to FragmentPagerAdapter() for allocating the fragments.

In other words, although the subclass allocates the fragments it is not the owner of them.

Since, as said above, the owner of the fragments is FragmentPagerAdapter, all fragment operations (in the sense of FragmentManager/FragmentTransaction) must only be done by FragmentPagerAdapter.

Trying to perform operations on these fragments may interfere with the normal operation of the ViewPager and cause undefined behavior.

In the case of this question, there is an attempt to remove one of the fragments used by the ViewPager outside of FragmentPagerAdapter which as explained is bad and probably triggered a sequence that ended with this exception.

When it is needed to dynamically remove/add/replace pages in a ViewPager the way to do it to call notifyDataSetChanged() on the adapter.

Good luck!

like image 175
HaimS Avatar answered Nov 13 '22 01:11

HaimS