Reputation: 1143
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);
}
Here I face a problem. When I goes out the activty and then return back , I want to show again my GameView.
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.
What should I do?
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);
......
}
Upvotes: 1
Views: 1446
Reputation: 11131
try this...
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...
Upvotes: 2
Reputation: 3322
You can't use the same view in multiple activities. Instead you should create a new instance of the view
like every time you have to create new instance
Const.gameView = new GameView(this);
Upvotes: 0
Reputation: 634
Put this code in oncreate if you have this peice of code in onresume
Upvotes: 0