我的代码收到错误"The specified child already has a parent. You must call removeView() on the child's parent



正如标题所读,当我运行我的应用程序时,我在LogCat中得到这个错误。这是错误发生后编写的代码:

public void coinAnim1() {
    RelativeLayout rl = (RelativeLayout) findViewById(R.id.mainlayoutid);
    ImageView coin1 = new ImageView(this);
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(30, 40);
    params.leftMargin = 50;
    coin1 = (ImageView) findViewById(R.id.coinid);
    Animation coinFall1 = AnimationUtils.loadAnimation(this,
            R.anim.coinanimation);
    coin1.startAnimation(coinFall1);
    rl.addView(coin1, params);
}
public void coinAnim2() {
    RelativeLayout rl2 = (RelativeLayout) findViewById(R.id.mainlayoutid);
    ImageView coin2 = new ImageView(this);
    RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(30, 40);
    params2.leftMargin = 50;
    coin2 = (ImageView) findViewById(R.id.coin2id);
    Animation coinFall1 = AnimationUtils.loadAnimation(this,
            R.anim.coinanimation);
    coin2.startAnimation(coinFall1);
    rl2.addView(coin2, params2);
}

LogCat表示行"rl"。addView(coin1, params);"特别导致错误。有人知道我该怎么做吗?还有类似的问题,但由于我是编码新手,我不知道如何根据我的问题调整答案。

任何帮助都是感激的。

问题解决:

Ashishduh通过替换行来解决这个问题:

rl.addView(coin1, params);  

与行:

coin1.setLayoutParams(params);  

希望这能帮助到一些人!3

视图coin1已经有一个父(您膨胀的RelativeLayout)。如果不把它从RelativeLayout中移除,你就不能把它分配给另一个父元素。

我认为你要做的是修改LayoutParams的coin1。而不是这样做:rl.addView(coin1, params);你只需要设置像这样的布局参数coin1.setLayoutParams(params);

从代码片段

RelativeLayout rl = (RelativeLayout) findViewById(R.id.mainlayoutid);
    ImageView coin1 = new ImageView(this);
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(30, 40);
    params.leftMargin = 50;
    coin1 = (ImageView) findViewById(R.id.coinid);

创建coin1 &coin2 ImageView以编程方式创建,因为你已经在xml中添加了这些,或者以编程方式创建ImageViewsxml

最新更新