Reputation: 141
Right now I have my MainActivity.java that extends the Activity class.
package com.divergent.tapdown1;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View PlayScreen = new PlayScreen(this);
setContentView(PlayScreen);
PlayScreen.setBackgroundColor(Color.BLACK);
}
}
This opens PlayScreen which extends View. I want to be able to open the new LoseScreen that I created from PlayScreen when a certain event occurs. The problem is the setContentView() is obviously part of the Activity class. How can I get around this?
Thanks!
EDIT:
if (playerBounds.bottom > rowBlock.top && playerBounds.top < rowBlock.bottom && (playerBounds.left < blockX1[row] || playerBounds.right > blockX2[row])) {
ViewGroup parent = (ViewGroup) getParent();
finalScore = score;
parent.addView(new PauseScreen(getContext()));
parent.bringToFront();
parent.setBackgroundResource(R.drawable.pausebackground);
}
Upvotes: 0
Views: 65
Reputation: 1200
There are several approaches you can take:
You can create a container View (e.g. a FrameLayout
), use it as your root view, and add the LoseScreen to it and remove the PlayScreen from it. You can then pass a reference to the container around if some other code needs to add/remove views.
View playScreen = new PlayScreen(this);
View container = new FrameLayout(this);
playScreen.setRootView(container);
container.addView(playScreen);
setContentView(container);
You can pass a reference to MainActivity
to the class that creates the LoseScreen. Since setContentView
is a public method, you can then just call setContentView
on it, e.g.:
Activity mainActivity = this;
playScreen.setMainActivity(mainActivity);
Then from within PlayScreen
:
mainActivity.setContentView(new LoseScreen(getContext()));
From within PlayScreen
, you can get the parent view using getParent()
and then, similar to the first approach, add the LoseScreen to it and remove the PlayScreen.
ViewGroup parent = (ViewGroup)getParent();
parent.addView(new LoseScreen(getContext()));
parent.removeView(this);
Upvotes: 1