Android“指定的孩子已经有了父母。”片段onCreateView()?

时间:2013-03-04 04:35:02

标签: android compiler-errors android-listfragment

我正在使用兼容包在我的Android应用程序中使用SherlockFragments。为fragments获取此错误。 FATAL EXCEPTION: main java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.我将这些片段添加为actionbar sherlock中的标签。当我第一次切换标签时它成功运行应用程序它正常工作,第二次它在onCreateView()中给出了上述错误..

这是onCreate()

中的代码
private static final String AD_UNIT_STANDARD_BANNER = "/6253334/dfp_example_ad/banner";
private DfpAdView adView;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState); 

    adView = new DfpAdView(getActivity(), AdSize.BANNER, AD_UNIT_STANDARD_BANNER);  
    adView.setAdListener(this);
}

这是我在片段onCreateView()中使用的代码。

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {     
    View view = inflater.inflate(R.layout.fragment_chats, container, false);         
    listview = (ListView) view.findViewById(android.R.id.list); 
    RelativeLayout layout = (RelativeLayout) view.findViewById(R.id.chats_inner_layout);

    adView.setId(111);
    adView.loadAd(new AdRequest());        
    RelativeLayout.LayoutParams add_lp = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    add_lp.addRule(RelativeLayout.BELOW, adView.getId());   
    listview.setLayoutParams(add_lp);

    //**** this is the line causing for error****/////
    layout.addView(adView);         
    return view;         
}

这是上面片段的

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/chats_main_layout"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:background="@color/app_lite_theme"
   android:orientation="vertical" >

   <RelativeLayout
      android:id="@+id/chats_inner_layout"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:orientation="vertical" >

      <ListView
          android:id="@android:id/list"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"
          android:layout_marginLeft="8dp"
          android:layout_marginRight="8dp"
          android:scrollbars="none" />

   </RelativeLayout>
</RelativeLayout>

这个相同的代码,我用于没有任何问题的正常工作的片段。我只面临片段问题。这里有什么问题 ?任何人都说  我解决这个问题。

1 个答案:

答案 0 :(得分:0)

我觉得这部分有些不对劲

  listview.setLayoutParams(add_lp);

应该是

 addView.setLayoutParams(add_lp);