Android Studio
We have a project (game) that we need to do android game, a space racing game and we're almost done. We just need to add a retry button and exit button on the game view. The code below is on my GamePlayScene.java and it doesn't have a XML file on the layout folder. They said that it is connected through the game itself. I'm super new to coding a game and on Java language. When I press the start button on the emulator it goes to MainActivty2.java and that MainActivity2 has a XML or on the layout folder but it doesn't have any designs on it, it doesn't have spaceship or anything that we can see if we run the game or start the game on the emulator. So I tried to add a button on that XML and when I tried to press the start button, the message appears "Unfortunately, SpaceRacing has stopped". I hope someone can understand me with this.
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Button button= new Button (this);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.WRAP_CONTENT);
params.topMargin = 0;
params.gravity = Gravity.TOP | Gravity.CENTER_HORIZONTAL;
button.setText("Retry");
addContentView(button, params);
// setContentView(tv);
button.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View v) {
Intent intent = new Intent(this, MainActivity2.class);
}
});
}
The bold letter or has " ** ** " on the code has a red font on the studio.
You need to start with a setContentView
so your activity will have an initial layout.
To that method you will pass either a view or a layout id.
So if for example you have a layout file named activity2_layout.xml
your onCreate
method should look something like this
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity2_layout)
And then you call your button with
findViewById(R.id.buttun_id)
And if you want to add the button there without XML, you first find your layout and then call
myLayout.addView(button)
This is really Android basics, you probably want to take a look at this before proceeding
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.