Error inflating class fragment - duplicate id/illegalargumentexception?

后端 未结 7 902
梦毁少年i
梦毁少年i 2020-12-02 17:05

I\'m trying make an app that I\'m building take a search term from the main activity, return results, and then have the results be clickable such that a detail could be view

7条回答
  •  遥遥无期
    2020-12-02 17:59

    It occurs when fragments are defined in XML (statically): FragmentManager doesn't manage child fragments if parent fragment is destroyed. Then, it breaks ("duplicate id" error) when the XML is inflated for the second time.

    I bypass this problem removing the XML fragment manually when parent is destroyed, with this code in the parent fragment:

    @Override
    public void onDestroyView() {
    
        FragmentManager fm = getFragmentManager();
    
        Fragment xmlFragment = fm.findFragmentById(R.id.XML_FRAGMENT_ID);
        if (xmlFragment != null) {
            fm.beginTransaction().remove(xmlFragment).commit();
        }
    
        super.onDestroyView();
    }
    

    Note for copypasters: XML_FRAGMENT_ID is the id of the fragment in the XML ;)


    Furthermore, I prefer a new class that wraps XML fragments. It simplyfies the code since you just need to extend your fragment class from it. Add this class to your project:

    package net.treboada.mytests.fragments;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentManager;
    import android.util.AttributeSet;
    
    public class XmlFragment extends Fragment {
    
        @Override
        public void onInflate(Activity activity, AttributeSet attrs,
                Bundle savedInstanceState) {
    
            FragmentManager fm = getFragmentManager();
            if (fm != null) {
                fm.beginTransaction().remove(this).commit();
            }
    
            super.onInflate(activity, attrs, savedInstanceState);
        }
    }
    

    Then, extend your XML fragment classes:

    package net.treboada.mytests.fragments;
    
    public class TestXmlFragment01 extends XmlFragment {
    
        // ...
    
    }
    

    and voilà! :)

提交回复
热议问题