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ò)誤棧信息定位的頁面的布局大概如下圖
這個(gè)頁面的布局,主頁面Activity包含viewpager管理著fragment數(shù)組(就是最常見的那種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)場,分析錯(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)類都做了什么
這部分是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過程
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è)賮砜聪翭ragment類mInLayout屬性的定義
//Fragment.java
// Set to true when the view has actually been inflated in its layout.
// 當(dāng)fragment的layout已經(jīng)被inflate過具温,則設(shè)為true
boolean mInLayout;
為什么要加載的fragment已經(jīng)存在了呢蚕涤?搞明白這個(gè),才算解決了問題铣猩,接著錯(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)系
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();
}
分析完它們之間的關(guān)系,我們應(yīng)該能發(fā)現(xiàn)峦椰,fragmentB是被FragmentActivity的FragmentManager加載龄寞,fragmentB和fragmentA為同級(jí)兄弟關(guān)系。當(dāng)fragmentB被加載汤功,除非顯式通過FragmentActivity的FragmentManager移除物邑,則只能等FragmentActivity被銷毀一起回收,這也就是解釋了為什么fragmentA銷毀滔金,fragmentB不一起銷毀色解,fragmentA重新創(chuàng)建,fragmentB已經(jīng)存在餐茵。
4. 解決方法
定位問題了科阎,該解決了,現(xiàn)在有三種方法
1.解決方法一
覆寫fragmentA的onDestroyView方法钟病,當(dāng)fragmentA銷毀的時(shí)候萧恕,手動(dòng)銷毀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來管理fragment票唆,這樣FragmentA銷毀的時(shí)候,fragmentB也一起銷毀
ChosenHeaderImageFragment fragment = ChosenHeaderImageFragment.getInstance();
getChildFragmentManager().beginTransaction()
.replace(R.id.banner_header_fragment, fragment)
.commit();
3.解決方法三
仍然靜態(tài)引入屹徘,但是使用fragmentA的onCreateView方法中的LayoutInflater來加載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)銷毀。第三種鉴吹,不同的LayoutInflater有什么差別嗎姨伟?
我們花點(diǎn)時(shí)間看看它們的差別
LayoutInflater mInflater = LayoutInflater.from(mContext);
LayoutInflater.java
直接調(diào)用系統(tǒng)服務(wù),沒什么需要注意的
/**
* 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;
}
接下來要翻源代碼了豆励,過程省略了夺荒,我直接放關(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é)一下伍玖,通過分析源代碼明白了,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);
}
}