1

我有一个类扩展名为 GameView 的视图。在 MainActivity 我把它作为 contentView:

    if(Const.gameView == null){
        Const.gameView = new GameView(this);
        Const.gameView.setViews(Const.chickenArr,Const.chickenViewArr,message,score_message , this.importantMessage  , this.showTimerMessage);
        setContentView(Const.gameView);

    }

在这里我面临一个问题。当我退出活动然后返回时,我想再次显示我的 GameView。

当我使用上面的代码时,当我再次回到 MainActivity 时,我没有看到我的 gameView。当我通过设置 setContentView(Const.gameView); 更改代码时 在“如果”之外我得到一个错误

11-10 22:17:35.821: E/AndroidRuntime(1580): Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

我该怎么办?

游戏视图:

public GameView(Context context) {
    super(context);     
    int picture = Const.a1;
    if(backgroundBitmap == null)
        backgroundBitmap = BitmapFactory.decodeResource(getResources(), picture);
    // TODO Auto-generated constructor stub
}

public void setViews(Chicken[] chickenArr, ChickenView[] chickenViewArr,Messages message , Messages messageScore,
        Messages gameoverMes , Messages showRemailTimeMes) {
    this.chickenArr = chickenArr;
    this.chickenViewArr = chickenViewArr;

    this.message=message;
    this.  messageScore =   messageScore;
    this.gameoverMes =gameoverMes;
    this.showRemailTimeMes=showRemailTimeMes;
}

   @Override
public void onDraw(Canvas canvas)
{
    canvas.drawBitmap(this.backgroundBitmap, 1, 1, null);

    //meassage
    this.message.onDraw(canvas);
        ......

}

4

3 回答 3

3

试试这个...

if(Const.gameView == null){
    Const.gameView = new GameView(this);
    Const.gameView.setViews(Const.chickenArr,Const.chickenViewArr,message,score_message , this.importantMessage  , this.showTimerMessage);
    setContentView(Const.gameView);
} else {
    ViewParent parent = Const.gameView.getParent();
    if(parent != null && parent instanceof ViewGroup) {
       ViewGroup viewGroup = (ViewGroup)parent;
       viewGroup.removeView(Const.gameView);
    }
  setContentView(Const.gameView);
}

我观察到您正在维护对 Const 类中的视图的静态引用。我建议你不要维护视图的静态引用,因为上下文与每个视图相关联,从而导致上下文泄漏......

于 2013-11-11T10:13:51.903 回答
0

如果您在 onresume 中有这段代码,请将此代码放入 oncreate

于 2013-11-11T09:54:25.180 回答
0

您不能在多个活动中使用相同的视图。相反,您应该创建视图的新实例

 like every time you have to create new instance
Const.gameView = new GameView(this);
于 2013-11-11T10:03:18.063 回答