我正在尝试添加一个布局片段,但我不断收到错误消息:
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 );
正确的做法是什么?
您使用 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 );
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句