[Android錯(cuò)誤排查]java.lang.IllegalArgumentException: Binary XML file line #6: Duplicate id 0x7f090e31...

1. 錯(cuò)誤信息描述

友盟錯(cuò)誤列表有這樣一條錯(cuò)誤記錄

[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]

完整的錯(cuò)誤棧信息如下

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. 界面布局描述

錯(cuò)誤棧信息定位的頁(yè)面的布局大概如下圖

1.png

這個(gè)頁(yè)面的布局,主頁(yè)面Activity包含viewpager管理著fragment數(shù)組(就是最常見(jiàn)的那種App,主界面由幾個(gè)tab組成,每個(gè)tab用一個(gè)fragment展示),其中一個(gè)fragment,就叫fragmentA靜態(tài)引入fragmentB作為fragmentA布局的一個(gè)view。

//fragmentA 靜態(tài)引入fragmentB作為布局的一個(gè)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. 錯(cuò)誤分析

錯(cuò)誤棧信息就是第一現(xiàn)場(chǎng),分析錯(cuò)誤棧信息,android.view.InflateException 是inflate xml文件報(bào)錯(cuò),
Error inflating class fragment 是inflate fragment報(bào)錯(cuò),
Duplicate id 0x7f090e31 ...... with another fragment for xxx.sns.fragment.ChosenHeaderImageFragment是inflate
ChosenHeaderImageFragment時(shí),發(fā)現(xiàn)ChosenHeaderImageFragment已經(jīng)在布局中加載了,就報(bào)異常。
我們?cè)僭敿?xì)看下錯(cuò)誤堆棧信息,看下各相關(guān)類(lèi)都做了什么
這部分是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已經(jīng)inflate完,創(chuàng)建fragment過(guò)程

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)

現(xiàn)在只看錯(cuò)誤棧最外層的信息,
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為空,創(chuàng)建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
    //這里就是報(bào)錯(cuò)的地方
    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;
}

我們找到報(bào)異常的位置,當(dāng)fragment的mInLayout屬性值為true,就拋出異常。我們?cè)賮?lái)看下Fragment類(lèi)mInLayout屬性的定義

//Fragment.java
// Set to true when the view has actually been inflated in its layout.
// 當(dāng)fragment的layout已經(jīng)被inflate過(guò),則設(shè)為true
boolean mInLayout;

為什么要加載的fragment已經(jīng)存在了呢?搞明白這個(gè),才算解決了問(wèn)題,接著錯(cuò)誤棧分析源代碼

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)

這里出現(xiàn)了FragmentActivity,BaseFragmentActivityHoneycomb,
FragmentController,F(xiàn)ragmentManagerImpl等class,先搞清它們之間的關(guān)系

2.jpg

FragmentActivity.java
FragmentActivity的成員變量mFragments是FragmentController類(lèi)型

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

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

FragmentController.java
FragmentController的成員變量mHost是FragmentHostCallback類(lèi)型

/**
 * 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類(lèi)型

/**
 * 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();
}

分析完它們之間的關(guān)系,我們應(yīng)該能發(fā)現(xiàn),fragmentB是被FragmentActivity的FragmentManager加載,fragmentB和fragmentA為同級(jí)兄弟關(guān)系。當(dāng)fragmentB被加載,除非顯式通過(guò)FragmentActivity的FragmentManager移除,則只能等FragmentActivity被銷(xiāo)毀一起回收,這也就是解釋了為什么fragmentA銷(xiāo)毀,fragmentB不一起銷(xiāo)毀,fragmentA重新創(chuàng)建,fragmentB已經(jīng)存在。

4. 解決方法

定位問(wèn)題了,該解決了,現(xiàn)在有三種方法

1.解決方法一

覆寫(xiě)fragmentA的onDestroyView方法,當(dāng)fragmentA銷(xiāo)毀的時(shí)候,手動(dòng)銷(xiāo)毀fragmentB。這個(gè)是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.解決方法二

靜態(tài)引入改為動(dòng)態(tài)引入,讓fragmentA的childFragmentManager來(lái)管理fragment,這樣FragmentA銷(xiāo)毀的時(shí)候,fragmentB也一起銷(xiāo)毀

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

仍然靜態(tài)引入,但是使用fragmentA的onCreateView方法中的LayoutInflater來(lái)加載layout

@Override
protected void initViews(Bundle savedInstanceState) {
    super.initViews(savedInstanceState);
    //此處如果不用全局的mInflater,xml靜態(tài)引用<fragment>的時(shí)候就會(huì)崩潰。
    //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的時(shí)候,確保fragmentB已經(jīng)銷(xiāo)毀。第三種,不同的LayoutInflater有什么差別嗎?
我們花點(diǎn)時(shí)間看看它們的差別

LayoutInflater mInflater = LayoutInflater.from(mContext);

LayoutInflater.java
直接調(diào)用系統(tǒng)服務(wù),沒(méi)什么需要注意的

    /**
     * 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;
    }

接下來(lái)要翻源代碼了,過(guò)程省略了,我直接放關(guān)鍵代碼了
FragmentManagerImpl.java
moveToState這個(gè)方法管理著Fragment不同狀態(tài)要做的事情,performCreateView執(zhí)行Fragment的創(chuàng)建

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版本有不同的實(shí)現(xiàn)方式,但基本上都是將
factory方法關(guān)聯(lián)到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 關(guān)聯(lián)到LayoutInflater,
因?yàn)镕ragmentManagerImpl已經(jīng)實(shí)現(xiàn)了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;
    }
}

總結(jié)一下,通過(guò)分析源代碼明白了,F(xiàn)ragment的回調(diào)方法

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

inflater關(guān)聯(lián)了mChildFragmentManager,這是跟LayoutInflater.from(mContext)的差別
但是這個(gè)額外的關(guān)聯(lián)有什么作用呢?接著看
LayoutInflater.java
到這,關(guān)聯(lián)的工廠方法有作用了,由mChildFragmentManager管理Fragment的創(chuàng)建,跟方法二的作用是一樣的

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);
            }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 嵌套Fragment的使用及常見(jiàn)錯(cuò)誤 嵌套Fragments (Nested Fragments), 是在Frag...
    圣騎士wind閱讀 6,770評(píng)論 0 24
  • Correctness AdapterViewChildren Summary: AdapterViews can...
    MarcusMa閱讀 9,052評(píng)論 0 6
  • 第65天/2次 2017、4.29 覺(jué)察日記 事實(shí):今天抽到一張彩虹卡,上面寫(xiě)著“玩是我當(dāng)下最重要的因素”。 覺(jué)察...
    甌姐姐閱讀 196評(píng)論 0 1
  • 人生最大的迷題:生從何處來(lái)?死往何處去?六祖大師說(shuō):我自知去處。如今六祖大師的肉身尚在,而他的真身去了哪里? 世界...
    知止山人閱讀 1,703評(píng)論 0 2
  • 今天您離開(kāi)了, 安詳?shù)拈]上了眼睛, 醫(yī)院的儀器跳動(dòng)的頻率緩緩的平靜。 告訴著我們…你離開(kāi)了。 九十多年的蒼茫歲月,...
    故我知行閱讀 507評(píng)論 0 0

友情鏈接更多精彩內(nèi)容