本文介绍了Android的 - 集内容视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类继承查看名为GameView。在MainActivity我把它作为内容查看:

I have a class extends View named GameView. In MainActivity I put it as 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);

    }

在这里,我面临的一个问题。当我走出activty,然后返回回来,我想再次表达我GameView。

Here I face a problem. When I goes out the activty and then return back , I want to show again my GameView.

当我用code以上,当我回来再在MainActivity,我没有看到我的gameView。
当我通过设置的setContentView(Const.gameView)改变code;外的如果我得到一个错误

When I use the code above , when I came back again to the MainActivity , I didn't see my gameView.When I change the code by setting the setContentView(Const.gameView); outside the "if" I get an error

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.

我应该怎么办?

GameView:

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

}

推荐答案

试试这个...

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

和我观察,你是维持在常量类浏览静态引用。我建议你​​语境与每个显示有关,从而导致上下文漏不维护浏览静态引用...

and I observed that you are maintaining static references to Views in Const class. I suggest you that don't maintain static reference for Views as Context is associated with every View and thus leads to leakage of Context...

这篇关于Android的 - 集内容视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 03:53