IllegalStateException: Can't change container ID of Fragment

后端 未结 10 1693
孤街浪徒
孤街浪徒 2020-11-29 04:18

Android platform: 3.1

I am trying to move a fragment from a container A to a container B. Here follows the code to accomplish this:

private void rea         


        
10条回答
  •  伪装坚强ぢ
    2020-11-29 05:11

    Is there any valid reason aside from poor programming principals, that you'd want to keep a reference to an existing fragment across an activity or two anyway? Rather than saving the state of the fragment and simply recreating it?

    I was creating fragments using:

        public static ContactsFragment mContactsFragment;
    
        public static ContactsFragment getInstance() {
        if (mContactsFragment == null) {
            mContactsFragment = new ContactsFragment();
        }
        return mContactsFragment;
    }
    

    I've done this since I learned Android but can't see why I'd want to refer to my fragment statically despite it being in everyone's examples. Originally I thought it was to refer to a Context statically, but you can always set this when you create a new fragment and saving a context anyway often leads to odd bugs later anyway.

    Why wouldn't you:

        public static ContactsFragment newInstance(Context c) {
        ContactsFragment mContactsFragment = new ContactsFragment();
        mContext = c;
        return mContactsFragment;
    }
    

    and simply save any work you've done on the fragment and recreate it when you need it again? Perhaps I can imagine if you were creating 100+ (news app?) you might not want to have to create them each time, rather store them in memory? Anyone?

提交回复
热议问题