2017-07-15 74 views
-1

我想添加一个布局片段,但我不断收到错误:如何包括布局片段的Android

Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first. 

这是碎片如何包含在rev_lay_drawer_nav.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:orientation="horizontal"> 

    <LinearLayout 
     android:id="@+id/helpAboutLL" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:orientation="vertical"> 

     <Button 
      android:id="@+id/about_bags_bttn" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:text="About BAGS" /> 

     <Button 
      android:id="@+id/help_bttn" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:src="@drawable/rev_dr_thinner_help_top" 
      android:text="Help" /> 

    </LinearLayout> 

</LinearLayout> 

这是我怎样,我称之为:

mContext = context; 

revLayDrawerLayoutInflater = LayoutInflater.from(mContext); 
revLayDrawerView = revLayDrawerLayoutInflater.inflate(R.layout.rev_lay_drawer_nav, null, false); 

LinearLayout helpAboutLL = (LinearLayout) revLayDrawerView.findViewById(R.id.helpAboutLL); 

LinearLayout revDrawerNavViewContainer = new LinearLayout(mContext); 
revDrawerNavViewContainer.setOrientation(LinearLayout.VERTICAL); 

revDrawerNavViewContainer.addView(helpAboutLL); 

瓦在正确的方式去呢?

+2

错误提供了很多info.The LinearLayout中与ID helpAboutLL有已经是您的XML定义的父视图。您正尝试为其分配一个新的父级,这是错误的,因为View不能是两个View父级的子级。你可以尝试创建一个没有初始LinearLayout的xml。这种方式helpAboutLL将有一个父项。我认为它会起作用。 – Giannis

回答

1

你使用findViewById的事实意味着你已经有了一个父布局的视图。

而你不能添加一个视图到另一个布局,而它有另一个父视图。


目前尚不清楚为什么你需要嵌套LinearLayouts因此改变你的XML

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

    <Button 
     android:id="@+id/about_bags_bttn" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:text="About BAGS" /> 

    <Button 
     android:id="@+id/help_bttn" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:src="@drawable/rev_dr_thinner_help_top" 
     android:text="Help" /> 

</LinearLayout> 

和膨胀,并添加只是

LinearLayout revDrawerNavViewContainer = new LinearLayout(mContext); 
revDrawerNavViewContainer.setOrientation(LinearLayout.VERTICAL); 

View helpAboutLL = revLayDrawerLayoutInflater.inflate(R.layout.rev_lay_drawer_nav, null, false); 
revDrawerNavViewContainer.addView(helpAboutLL);