【Android异常】The specified child already has a parent. You must call removeView() on the child's parent first.
在学习Activity中动态添加和删除Fragment时,遇到错误信息:
Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
信息补充:
使用FragmentActvitiy,向FragmentLayout 添加 Fragment
错误原因:
出现此错误的根本问题是当前VIEW已经在别的View中,作为别的子View,而你现在又要将当前VIEW放在别的View中,就会抛出这类错误信息。解决方法是是先找到当前VIEW的父VIEW,在父VIEW中调用removeView(),移除当前VIEW,就可以解决此问题了。
具体而言,错误在定义的Fragment的类中返回view的调用,应该是添加在root根view了。(暂时不明所以,mark下)
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.preference_fragment, container);
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.preference_fragment, container);
解决办法:
View v = inflater.inflate(R.layout.preference_fragment, container, false);