Description:
當一個child view已經被加到A parent view,若有另一個B parent view再對該child view進行add view的動作,即會產生該Error。
簡單的說child view只能屬於一個parent view。
Solution:
在child view加入B parent view之前,A parent view 必須先移除child view。
Example:
最外層的RelativeLayout為了方便操縱,給予id為root_view,內層的text_view即為child view的角色。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/root_view"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</RelativeLayout>
在第17行已經設定完UI Layout,也就是說根據xml的內容,mTextView已經被加到mRootParentView中。
第24行有另一個Parent View對mTextView進行addView的動作,若沒有在第21行 remove child view,即會產生錯誤。
package com.foxx.errortest;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity
{
private TextView mTextView;
private RelativeLayout mRootParentView;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRootParentView = (RelativeLayout) findViewById(R.id.root_view);
mTextView = (TextView) findViewById(R.id.text_view);
mRootParentView.removeView(mTextView);
RelativeLayout anotherParentLayout = new RelativeLayout(this);
anotherParentLayout.addView(mTextView);
}
}