您的位置:首页 > 移动开发 > Android开发

Android 开发 Tip 4 -- You must call removeView() on the child's parent first

2017-04-15 23:43 711 查看
转载请注明出处:http://blog.csdn.net/crazy1235/article/details/70188640

问题描述:

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

at android.view.ViewGroup.addViewInner(ViewGroup.java:4417)
at android.view.ViewGroup.addView(ViewGroup.java:4258)
at android.view.ViewGroup.addView(ViewGroup.java:4198)
at android.view.ViewGroup.addView(ViewGroup.java:4171)


通常发生在动态添加view的时候,要添加的view有parent view。所以报这个错误。

还原现场

LayoutInflater inflater = getLayoutInflater();
LinearLayout tempLayout = (LinearLayout) inflater.inflate(R.layout.temp_layout, null);
TextView textView = (TextView) tempLayout.findViewById(R.id.text_view);
rootLayout.addView(textView);


temp_layout.xml

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

<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:srcCompat="@drawable/child" />

<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hope is a good thing, maybe the best of things" />

</LinearLayout>


解决方案

先将要添加的view从其原先parent viewgroup中移除。

TextView textView = (TextView) tempLayout.findViewById(R.id.text_view);
tempLayout.removeView(textView);
rootLayout.addView(textView);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐