我有一个名为GameView的类扩展View。在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)来更改代码时;在“if”之外我收到错误
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);
......
}
答案 0 :(得分: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类中维护对Views的静态引用。我建议你不要为Views维护静态引用,因为Context与每个View相关联,从而导致Context的泄漏......
答案 1 :(得分:0)
如果在onresume
中有这段代码,请将此代码放在oncreate中答案 2 :(得分:0)
您不能在多个活动中使用相同的视图。相反,您应该创建视图的新实例
like every time you have to create new instance
Const.gameView = new GameView(this);