我试图添加一个布局片段,但我一直收到错误:
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 );
正确的方法是什么?
答案 0 :(得分: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 );