[Android错误排查]java.lang.IllegalArgumentException: Binary XML file line #6: Duplicate id 0x7f090e31...

1. 错误信息描述

友盟错误列表有这样一条错误记录

[Caused by: java.lang.IllegalArgumentException: Binary XML file line #6: Duplicate id 0x7f090e31, tag null, or parent id 0xffffffff with another fragment for xxx.fragment.ChosenHeaderImageFragment]

完整的错误栈信息如下

android.view.InflateException: Binary XML file line #6: Binary XML file line #6: Error inflating class fragment
Caused by: android.view.InflateException: Binary XML file line #6: Error inflating class fragment
Caused by: java.lang.IllegalArgumentException: Binary XML file line #6: Duplicate id 0x7f090e31, tag null, or parent id 0xffffffff with another fragment for xxx.sns.fragment.ChosenHeaderImageFragment
    at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:3447)
    at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:120)
    at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:378)
    at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:33)
    at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:79)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:802)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:752)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:883)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:846)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:522)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:430)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:377)
    at xxx.sns.fragment.CarBBSChosenFragment.initHeaderView(CarBBSChosenFragment.java:198)
    

2. 界面布局描述

错误栈信息定位的页面的布局大概如下图

1.png

这个页面的布局,主页面Activity包含viewpager管理着fragment数组(就是最常见的那种App,主界面由几个tab组成,每个tab用一个fragment展示),其中一个fragment,就叫fragmentA静态引入fragmentB作为fragmentA布局的一个view。

//fragmentA 静态引入fragmentB作为布局的一个view
@Override
protected void initViews(Bundle savedInstanceState) {
    super.initViews(savedInstanceState);
    LayoutInflater mInflater = LayoutInflater.from(mContext);
    View header = mInflater.inflate(R.layout.special_header_fragment, null);
    mAdapter.addHeaderView(header);
}

special_header_fragment.xml

<!--special_header_fragment.xml-->
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <fragment
        android:id="@+id/special_header_fragment"
        android:name="com.yiche.price.sns.fragment.ChosenHeaderImageFragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</RelativeLayout>

3. 错误分析

错误栈信息就是第一现场,分析错误栈信息,android.view.InflateException 是inflate xml文件报错,
Error inflating class fragment 是inflate fragment报错,
Duplicate id 0x7f090e31 ...... with another fragment for xxx.sns.fragment.ChosenHeaderImageFragment是inflate
ChosenHeaderImageFragment时,发现ChosenHeaderImageFragment已经在布局中加载了,就报异常。
我们再详细看下错误堆栈信息,看下各相关类都做了什么
这部分是LayoutInflater加载xml
LayoutInflater mInflater = LayoutInflater.from(mContext);
View header = mInflater.inflate(R.layout.special_header_fragment, null);

at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:802)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:752)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:883)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:846)
at android.view.LayoutInflater.inflate(LayoutInflater.java:522)
at android.view.LayoutInflater.inflate(LayoutInflater.java:430)
at android.view.LayoutInflater.inflate(LayoutInflater.java:377)

这部分是fragment已经inflate完,创建fragment过程

at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:3447)
at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:120)
at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:378)
at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:33)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:79)

现在只看错误栈最外层的信息,
FragmentManagerImpl的onCreateView方法

@Override
public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
    ......
    // If we restored from a previous state, we may already have
    // instantiated this fragment from the state and should use
    // that instance instead of making a new one.
    // findFragmentById(id),从FragmentManager查找存在的fragment
    Fragment fragment = id != View.NO_ID ? findFragmentById(id) : null;
    if (fragment == null && tag != null) {
        fragment = findFragmentByTag(tag);
    }
    if (fragment == null && containerId != View.NO_ID) {
        fragment = findFragmentById(containerId);
    }
    //如果fragment为空,创建fragment
    if (fragment == null) {
        fragment = Fragment.instantiate(context, fname);
        fragment.mFromLayout = true;
        fragment.mFragmentId = id != 0 ? id : containerId;
        fragment.mContainerId = containerId;
        fragment.mTag = tag;
        fragment.mInLayout = true;
        fragment.mFragmentManager = this;
        fragment.mHost = mHost;
        fragment.onInflate(mHost.getContext(), attrs, fragment.mSavedFragmentState);
        addFragment(fragment, true);
    } 
    //fragment不为空,且mInLayout为true
    //这里就是报错的地方
    else if (fragment.mInLayout) {
        // A fragment already exists and it is not one we restored from
        // previous state.
        throw new IllegalArgumentException(attrs.getPositionDescription()
                + ": Duplicate id 0x" + Integer.toHexString(id)
                + ", tag " + tag + ", or parent id 0x" + Integer.toHexString(containerId)
                + " with another fragment for " + fname);
    } else {
        // This fragment was retained from a previous instance; get it
        // going now.
        fragment.mInLayout = true;
        fragment.mHost = mHost;
        // If this fragment is newly instantiated (either right now, or
        // from last saved state), then give it the attributes to
        // initialize itself.
        if (!fragment.mRetaining) {
            fragment.onInflate(mHost.getContext(), attrs, fragment.mSavedFragmentState);
        }
    }
    ......
    return fragment.mView;
}

我们找到报异常的位置,当fragment的mInLayout属性值为true,就抛出异常。我们再来看下Fragment类mInLayout属性的定义

//Fragment.java
// Set to true when the view has actually been inflated in its layout.
// 当fragment的layout已经被inflate过,则设为true
boolean mInLayout;

为什么要加载的fragment已经存在了呢?搞明白这个,才算解决了问题,接着错误栈分析源代码

at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:3447)
at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:120)
at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:378)
at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:33)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:79)

这里出现了FragmentActivity,BaseFragmentActivityHoneycomb,
FragmentController,FragmentManagerImpl等class,先搞清它们之间的关系

2.jpg

FragmentActivity.java
FragmentActivity的成员变量mFragments是FragmentController类型

final FragmentController mFragments = FragmentController.createController(new HostCallbacks());

  class HostCallbacks extends FragmentHostCallback<FragmentActivity> {
     ......
  }
}

FragmentController.java
FragmentController的成员变量mHost是FragmentHostCallback类型

/**
 * Provides integration points with a {@link FragmentManager} for a fragment host.
 * <p>
 * It is the responsibility of the host to take care of the Fragment's lifecycle.
 * The methods provided by {@link FragmentController} are for that purpose.
 */
public class FragmentController {
    private final FragmentHostCallback<?> mHost;

    /**
     * Returns a {@link FragmentController}.
     */
    public static final FragmentController createController(FragmentHostCallback<?> callbacks) {
        return new FragmentController(callbacks);
    }

    private FragmentController(FragmentHostCallback<?> callbacks) {
        mHost = callbacks;
    }

    /**
     * Instantiates a Fragment's view.
     *
     * @param parent The parent that the created view will be placed
     * in; <em>note that this may be null</em>.
     * @param name Tag name to be inflated.
     * @param context The context the view is being created in.
     * @param attrs Inflation attributes as specified in XML file.
     *
     * @return view the newly created view
     */
    public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
        return mHost.mFragmentManager.onCreateView(parent, name, context, attrs);
    }
}

FragmentHostCallback.java
FragmentHostCallback的成员变量mFragmentManager是FragmentManagerImpl类型

/**
 * Integration points with the Fragment host.
 * <p>
 * Fragments may be hosted by any object; such as an {@link Activity}. In order to
 * host fragments, implement {@link FragmentHostCallback}, overriding the methods
 * applicable to the host.
 */
public abstract class FragmentHostCallback<E> extends FragmentContainer {
    final FragmentManagerImpl mFragmentManager = new FragmentManagerImpl();
}

分析完它们之间的关系,我们应该能发现,fragmentB是被FragmentActivity的FragmentManager加载,fragmentB和fragmentA为同级兄弟关系。当fragmentB被加载,除非显式通过FragmentActivity的FragmentManager移除,则只能等FragmentActivity被销毁一起回收,这也就是解释了为什么fragmentA销毁,fragmentB不一起销毁,fragmentA重新创建,fragmentB已经存在。

4. 解决方法

定位问题了,该解决了,现在有三种方法

1.解决方法一

覆写fragmentA的onDestroyView方法,当fragmentA销毁的时候,手动销毁fragmentB。这个是stackoverflow提到的解决办法
https://stackoverflow.com/questions/27589590/error-inflating-class-fragment-duplicate-id-tag-null-or-parent-id-with-anoth

//FragmentA
@Override
public void onDestroyView() {
  super.onDestroyView();
  Fragment f = getFragmentManager().findFragmentById(R.id.special_header_fragment);
  if(f != null){
      getFragmentManager().beginTransaction().remove(f).commit();
  }
}
2.解决方法二

静态引入改为动态引入,让fragmentA的childFragmentManager来管理fragment,这样FragmentA销毁的时候,fragmentB也一起销毁

ChosenHeaderImageFragment fragment = ChosenHeaderImageFragment.getInstance();
getChildFragmentManager().beginTransaction()
                .replace(R.id.banner_header_fragment, fragment)
                .commit();
3.解决方法三

仍然静态引入,但是使用fragmentA的onCreateView方法中的LayoutInflater来加载layout

@Override
protected void initViews(Bundle savedInstanceState) {
    super.initViews(savedInstanceState);
    //此处如果不用全局的mInflater,xml静态引用<fragment>的时候就会崩溃。
    //mInflater为onCreateView方法中定义的inflater
    View header = mInflater.inflate(R.layout.special_header_fragment, null);
    mAdapter.addHeaderView(header);
}
//fragment onCreateView 的方法签名
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
            @Nullable Bundle savedInstanceState) {
  return null;
}

前两种方法比较好理解,就是加载fragmentB的时候,确保fragmentB已经销毁。第三种,不同的LayoutInflater有什么差别吗?
我们花点时间看看它们的差别

LayoutInflater mInflater = LayoutInflater.from(mContext);

LayoutInflater.java
直接调用系统服务,没什么需要注意的

    /**
     * Obtains the LayoutInflater from the given context.
     */
    public static LayoutInflater from(Context context) {
        LayoutInflater LayoutInflater =
                (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (LayoutInflater == null) {
            throw new AssertionError("LayoutInflater not found.");
        }
        return LayoutInflater;
    }

Fragment.java

    /**
     * Called to have the fragment instantiate its user interface view.
     * This is optional, and non-graphical fragments can return null (which
     * is the default implementation).  This will be called between
     * {@link #onCreate(Bundle)} and {@link #onActivityCreated(Bundle)}.
     * 
     * <p>If you return a View from here, you will later be called in
     * {@link #onDestroyView} when the view is being released.
     * 
     * @param inflater The LayoutInflater object that can be used to inflate
     * any views in the fragment,
     * @param container If non-null, this is the parent view that the fragment's
     * UI should be attached to.  The fragment should not add the view itself,
     * but this can be used to generate the LayoutParams of the view.
     * @param savedInstanceState If non-null, this fragment is being re-constructed
     * from a previous saved state as given here.
     * 
     * @return Return the View for the fragment's UI, or null.
     */
    @Nullable
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
            @Nullable Bundle savedInstanceState) {
        return null;
    }

接下来要翻源代码了,过程省略了,我直接放关键代码了
FragmentManagerImpl.java
moveToState这个方法管理着Fragment不同状态要做的事情,performCreateView执行Fragment的创建

void moveToState(Fragment f, int newState, int transit, int transitionStyle, boolean keepActive) {
    f.mView = f.performCreateView(f.getLayoutInflater(f.mSavedFragmentState), container, f.mSavedFragmentState);
}

Fragment.java

View performCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
  if (mChildFragmentManager != null) {
      mChildFragmentManager.noteStateNotSaved();
  }
  return onCreateView(inflater, container, savedInstanceState);
}

/**
  * Hack so that DialogFragment can make its Dialog before creating
  * its views, and the view construction can use the dialog's context for
  * inflation.  Maybe this should become a public API. Note sure.
  * @hide
  */
  @RestrictTo(GROUP_ID)
public LayoutInflater getLayoutInflater(Bundle savedInstanceState) {
  LayoutInflater result = mHost.onGetLayoutInflater();
  getChildFragmentManager(); // Init if needed; use raw implementation below.
  LayoutInflaterCompat.setFactory(result, mChildFragmentManager.getLayoutInflaterFactory());
  return result;
}

LayoutInflaterCompat.java
setFactory方法不同android版本有不同的实现方式,但基本上都是将
factory方法关联到inflater

    /**
     * Attach a custom Factory interface for creating views while using
     * this LayoutInflater. This must not be null, and can only be set once;
     * after setting, you can not change the factory.
     *
     * @see LayoutInflater#setFactory(android.view.LayoutInflater.Factory)
     */
    public static void setFactory(LayoutInflater inflater, LayoutInflaterFactory factory) {
        IMPL.setFactory(inflater, factory);
    }

    static final LayoutInflaterCompatImpl IMPL;
    static {
        final int version = Build.VERSION.SDK_INT;
        if (version >= 21) {
            IMPL = new LayoutInflaterCompatImplV21();
        } else if (version >= 11) {
            IMPL = new LayoutInflaterCompatImplV11();
        } else {
            IMPL = new LayoutInflaterCompatImplBase();
        }
    }

Fragment.java
这里将mChildFragmentManager 关联到LayoutInflater,
因为FragmentManagerImpl已经实现了LayoutInflaterFactory 接口

// Private fragment manager for child fragments inside of this one.
FragmentManagerImpl mChildFragmentManager;
/**
  * Hack so that DialogFragment can make its Dialog before creating
  * its views, and the view construction can use the dialog's context for
  * inflation.  Maybe this should become a public API. Note sure.
  * @hide
  */
  @RestrictTo(GROUP_ID)
public LayoutInflater getLayoutInflater(Bundle savedInstanceState) {
  LayoutInflater result = mHost.onGetLayoutInflater();
  getChildFragmentManager(); // Init if needed; use raw implementation below.
  LayoutInflaterCompat.setFactory(result, mChildFragmentManager.getLayoutInflaterFactory());
  return result;
}
/**
 * Container for fragments associated with an activity.
 */
final class FragmentManagerImpl extends FragmentManager implements LayoutInflaterFactory{
    LayoutInflaterFactory getLayoutInflaterFactory() {
        return this;
    }
}

总结一下,通过分析源代码明白了,Fragment的回调方法

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
            @Nullable Bundle savedInstanceState)

inflater关联了mChildFragmentManager,这是跟LayoutInflater.from(mContext)的差别
但是这个额外的关联有什么作用呢?接着看
LayoutInflater.java
到这,关联的工厂方法有作用了,由mChildFragmentManager管理Fragment的创建,跟方法二的作用是一样的

View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
            boolean ignoreThemeAttr) {
try {
            View view;
            if (mFactory2 != null) {
                view = mFactory2.onCreateView(parent, name, context, attrs);
            } else if (mFactory != null) {
                view = mFactory.onCreateView(name, context, attrs);
            } else {
                view = null;
            }

            if (view == null && mPrivateFactory != null) {
                view = mPrivateFactory.onCreateView(parent, name, context, attrs);
            }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,233评论 6 495
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,357评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 159,831评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,313评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,417评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,470评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,482评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,265评论 0 269
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,708评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,997评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,176评论 1 342
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,827评论 4 337
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,503评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,150评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,391评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,034评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,063评论 2 352

推荐阅读更多精彩内容

  • 嵌套Fragment的使用及常见错误 嵌套Fragments (Nested Fragments), 是在Frag...
    圣骑士wind阅读 6,627评论 0 24
  • Correctness AdapterViewChildren Summary: AdapterViews can...
    MarcusMa阅读 8,857评论 0 6
  • 第65天/2次 2017、4.29 觉察日记 事实:今天抽到一张彩虹卡,上面写着“玩是我当下最重要的因素”。 觉察...
    瓯姐姐阅读 165评论 0 1
  • 人生最大的迷题:生从何处来?死往何处去?六祖大师说:我自知去处。如今六祖大师的肉身尚在,而他的真身去了哪里? 世界...
    知止山人阅读 1,560评论 0 2
  • 今天您离开了, 安详的闭上了眼睛, 医院的仪器跳动的频率缓缓的平静。 告诉着我们…你离开了。 九十多年的苍茫岁月,...
    故我知行阅读 484评论 0 0