java.lang.IllegalStateException: Can't change tag of fragment

后端 未结 6 1152
情书的邮戳
情书的邮戳 2020-12-05 07:39

Hi i am getting this error while using a pageViwer and Adapter to slide across 3 fragments.

here is my pageAdapter

public class FreedomPageAdapter ex         


        
相关标签:
6条回答
  • 2020-12-05 07:53

    It's probably because you're adding the same fragment instance three times to the list. You should create a new instance for each page.

    Also, I suggest looking into FragmentStatePagerAdapter if you're not too far into development. It may be a better choice if you want to refresh the content of the fragments from the main activity.

    0 讨论(0)
  • 2020-12-05 08:00

    You have created an instance of SubscribedFragment() class

    savedListFragment = new SubscribedFragment();
    

    and then you passed the list of this objects into ViewPager Adpater:

    FreedomPageAdapter(FragmentManager fm, List<Fragment> listFragment)
    

    which receives List of Fragment type in its constructor. Since the constructor receives List of Fragment type, try to cast each savedListFragment into Fragment before you add it to the list and then pass it to the adpater's constructor:

    fragmentList.add((Fragment)savedListFragment);
    viewPager.setAdapter(new FreedomPageAdapter(fragmentManager(), fragmentList));
    
    0 讨论(0)
  • 2020-12-05 08:07

    It is probably, you are sending the fragment instance null. Never ever send the fragment instance null.

        public static MyFragment getInstance() {
        MyFragment myFragment = new MyFragment();
        return myFragment;
    }
    

    And In pager adapter always use the @Override public Fragment getItem(int position) { return fragments[position]; }

    or

      @Override
    public Fragment getItem(int position) {
        return fragments.get(position);
    }
    

    as per your list of fragment. Also please prefer the link FragmentPagerAdapter

    Notes :- Never ever use context memory as a static

    0 讨论(0)
  • 2020-12-05 08:07

    In my case It was due to returning some null fragment, which was not handled in the getItem(position) function. Hope it helps someone.

    0 讨论(0)
  • 2020-12-05 08:09

    The following method should return one fragment for each tab:

    @Override
    public Fragment getItem(int position) {
        //Add some code
        //to verify that it will not return null
        return listFragment.get(position);
    }
    

    The code is fine, but make sure that the listFragment contains three different Fragment's, and the fragment is not null.

    0 讨论(0)
  • 2020-12-05 08:16

    In my case, I was not returning a fragment Instance for a particular position. I think FragmentPagerAdapter is receiving null in place of the TAG. That's why it's showing "Can't change tag of fragment" Correct me if I am wrong.

    0 讨论(0)
提交回复
热议问题