Fragment使用时出现 java.lang.IllegalStateException
标签(空格分隔): Android Fragment View
在写侧栏滑动UI时,切换不同选项时,Fragment切换程序终止
报错:
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:3880)
at android.view.ViewGroup.addView(ViewGroup.java:3733)
at android.view.ViewGroup.addView(ViewGroup.java:3678)
at android.view.ViewGroup.addView(ViewGroup.java:3654)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:905)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.app.BackStackRecord.run(BackStackRecord.java:833)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1452)
at android.app.FragmentManagerImpl1.run(FragmentManager.java:447)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5466)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:938)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:733)
错误原因便是:
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child’s parent first
出现此错误的根本问题是当前VIEW已经在别的View中,作为别的子View,而你现在又要将当前VIEW放在别的View中,就会抛出这类错误信息。解决方法是是先找到当前VIEW的父VIEW,在父VIEW中调用removeView(),移除当前VIEW,就可以解决此问题了.
此时Fragment代码如下:
public class ChooseAreaFragment extends Fragment{
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.choose_area,container);
listView = (ListView) view.findViewById(R.id.list_view);
titleText = (TextView) view.findViewById(R.id.title_text);
adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1,dataList);
listView.setAdapter(adapter);
myWeatherDB = MyWeatherDB.getInstance(getActivity());
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (currentLevel == LEVEL_PROVINCE) {
selectProvince = provinceList.get(position);
queryCities();
} else if (currentLevel == LEVEL_CITY) {
selectCity = cityList.get(position);
queryCounties();
}
}
});
Log.d("xyz onCreateView","true");
queryProvinces();
return view;
}
}
网络上找到一个解决方案:
View view = inflater.inflate(R.layout.choose_area,container);
改为
View view = inflater.inflate(R.layout.choose_area,container,false);
实际测试解决了这个问题。
原理是怎么样的呢,false是什么作用?
查看API源码:
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
final Resources res = getContext().getResources();
if (DEBUG) {
Log.d(TAG, "INFLATING from resource: \"" + res.getResourceName(resource) + "\" ("
+ Integer.toHexString(resource) + ")");
}
final XmlResourceParser parser = res.getLayout(resource);
try {
return inflate(parser, root, attachToRoot);
} finally {
parser.close();
}
}
这里调用了另一个方法
查看API源码:
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
synchronized (mConstructorArgs) {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate");
final Context inflaterContext = mContext;
final AttributeSet attrs = Xml.asAttributeSet(parser);
Context lastContext = (Context) mConstructorArgs[0];
mConstructorArgs[0] = inflaterContext;
View result = root;
try {
// Look for the root node.
int type;
while ((type = parser.next()) != XmlPullParser.START_TAG &&
type != XmlPullParser.END_DOCUMENT) {
// Empty
}
if (type != XmlPullParser.START_TAG) {
throw new InflateException(parser.getPositionDescription()
+ ": No start tag found!");
}
final String name = parser.getName();
if (DEBUG) {
System.out.println("**************************");
System.out.println("Creating root view: "
+ name);
System.out.println("**************************");
}
if (TAG_MERGE.equals(name)) {
if (root == null || !attachToRoot) {
throw new InflateException("<merge /> can be used only with a valid "
+ "ViewGroup root and attachToRoot=true");
}
rInflate(parser, root, inflaterContext, attrs, false);
} else {
// Temp is the root view that was found in the xml
final View temp = createViewFromTag(root, name, inflaterContext, attrs);
ViewGroup.LayoutParams params = null;
if (root != null) {
if (DEBUG) {
System.out.println("Creating params from root: " +
root);
}
// Create layout params that match root, if supplied
params = root.generateLayoutParams(attrs);
if (!attachToRoot) {
// Set the layout params for temp if we are not
// attaching. (If we are, we use addView, below)
temp.setLayoutParams(params);
}
}
if (DEBUG) {
System.out.println("-----> start inflating children");
}
// Inflate all children under temp against its context.
rInflateChildren(parser, temp, attrs, true);
if (DEBUG) {
System.out.println("-----> done inflating children");
}
// We are supposed to attach all the views we found (int temp)
// to root. Do that now.
if (root != null && attachToRoot) {
root.addView(temp, params);
}
// Decide whether to return the root that was passed in or the
// top view found in xml.
if (root == null || !attachToRoot) {
result = temp;
}
}
} catch (XmlPullParserException e) {
InflateException ex = new InflateException(e.getMessage());
ex.initCause(e);
throw ex;
} catch (Exception e) {
InflateException ex = new InflateException(
parser.getPositionDescription()
+ ": " + e.getMessage());
ex.initCause(e);
throw ex;
} finally {
// Don't retain static reference on context.
mConstructorArgs[0] = lastContext;
mConstructorArgs[1] = null;
}
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
return result;
}
}
直接看核心部分的代码:
if (root != null) {
if (DEBUG) {
System.out.println("Creating params from root: " +
root);
}
// Create layout params that match root, if supplied
params = root.generateLayoutParams(attrs);
if (!attachToRoot) {
// Set the layout params for temp if we are not
// attaching. (If we are, we use addView, below)
temp.setLayoutParams(params);
}
}
...
// We are supposed to attach all the views we found (int temp)
// to root. Do that now.
if (root != null && attachToRoot) {
root.addView(temp, params);
}
// Decide whether to return the root that was passed in or the
// top view found in xml.
if (root == null || !attachToRoot) {
result = temp;
}
个人理解是设置了false该方法就没有把这个View添加的root中,使用了一个临时变量(temp翻译的,感觉好理解)。测试了一下如果不用false就会出现这个错误。应该是在Fragment被使用前,该View已经被加载进root里了。