Fragment already added IllegalStateException

前端 未结 11 1430
一向
一向 2020-11-28 07:42

I use this method on my container Activity to show a BFrag

public void showBFrag()
{
    // Start a new FragmentTransaction
    FragmentTransaction fragmentT         


        
相关标签:
11条回答
  • 2020-11-28 07:55

    This code is working fine for me. try this

    ((MiActivity)getActivity()).addAccount = new AddAccount();
    ((MiActivity)getActivity()).addAccount.setArguments(params);
    fragmentManager = getActivity().getSupportFragmentManager();
    fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.fragment_container((MiActivity)getActivity()).addAccount);
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit();
    
    0 讨论(0)
  • 2020-11-28 07:56

    In the end my workaround was to execute remove() of the previous fragment and add() the new one. Although that's what replace() method was meant to do.

    But I am still guessing why replace() method didn't work properly in this case. It is really weird and I want to discard that it is because I am misunderstanding something or doing something wrong.

    0 讨论(0)
  • 2020-11-28 07:56

    Removing setOffscreenPageLimit from Viewpager solved my issue. Thanks.

    0 讨论(0)
  • 2020-11-28 07:57

    I used this:

    if (getFragmentManager().findFragmentByTag(newFragment.getClass().getName()) != null) {
       transaction.remove(newFragment);
     }
    

    and added fragment with

    MyFragment frag = new MyFragment(); 
    transaction.add(R.id.container, frag, MyFragment.class.getName())
    

    MyFragment.class.getName() stands for tag

    0 讨论(0)
  • 2020-11-28 07:57

    I tried calling FragmentTransaction.remove() from onTabUnselected() and it worked around this bug.

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        ft.add(R.id.fragment_container, fragment, null);
    }
    
    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        ft.remove(fragment);
    }
    
    0 讨论(0)
  • 2020-11-28 07:58

    Solved it by looping through my fragments and checking if isAdded() is true, then removing that fragment. More details here.

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