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


转载请注明出处: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


<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);

你可能感兴趣的:(Android开发,Android问题总结,Android从零单排)