Android 以编程方式替换LinearLayout中的视图

Android 以编程方式替换LinearLayout中的视图,android,android-layout,Android,Android Layout,我有一个布局: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height=

我有一个布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="horizontal"
          android:layout_width="match_parent"
          android:layout_height="100dp"
          android:background="#535353">

<TextView
    android:id="@+id/promo"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="5dp"
    android:padding="5dp"
    android:layout_weight="1"
    />

<TextView
    android:id="@+id/title"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="5dp"
    android:padding="5dp"
    android:layout_weight="1"
    />
</LinearLayout>
但是,我得到错误:java.lang.IllegalStateException:指定的子级已经有父级。必须首先对子级的父级调用removeView()


那么,你能帮我吗?我怎样才能做到这一点?

你想实现什么?如果您想替换它们,为什么不在XML本身中对它们重新排序呢?或者请详细解释您的需求。我想创建许多不同的视图,这些视图基于此布局。他们都有头衔和宣传片,但位置不同,规模也不同。所以,我想在代码中动态地移动和更改它的位置(和大小)AdView@pskink,你说得对!我添加了新的父视图(RelativeLayout->LinearLayout->promoView)并更改了代码ViewGroup vg=((ViewGroup)promo.getParent());vg.removeView(promo);vg.addView(promo);现在一切都好了。谢谢
public class AdView extends LinearLayout{

TextView promo;


public AdView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
}

private void init() {
    LayoutInflater.from(getContext()).inflate(R.layout.view, this);
    promo = (TextView) findViewById(R.id.promo);
    title = (TextView) findViewById(R.id.title);
}

private void changePosition() {
    removeView(promo);
    addView(promo);
}