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. 界面布局描述
错误栈信息定位的页面的布局大概如下图
这个页面的布局, 主页面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
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,先搞清它们之间的关系
FragmentActivity.java
FragmentActivity的成员变量mFragments是FragmentController类型
final FragmentController mFragments = FragmentController.createController(new HostCallbacks());
class HostCallbacks extends FragmentHostCallback {
......
}
}
FragmentController.java
FragmentController的成员变量mHost是FragmentHostCallback类型
/**
* Provides integration points with a {@link FragmentManager} for a fragment host.
*
* 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; note that this may be null.
* @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.
*
* 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 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静态引用的时候就会崩溃。
//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)}.
*
* 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);
}
}