Android, finish()ing
I am making a simple app to learn Android at the same time, I am very much a newbie.
So far this is what i have:
the app opens into levels.java
which has 8 buttons (in an xml file), when button 8 is clicked,I have this code:
public void button_clicked8(View v) {
startActivity(new Intent(this, GameScreen.class));
}
which launches my gamescreen activity, after playing my simple addition game, I have a button that says "end" which calls a function with a finish()
in it, it also s开发者_运维知识库ets a variable gameover=true;
, this sends me back to levels.java
but if I press the button 8 again, it does send me to Gamescreen but I find that gameover=true;
is still set :(
Why is that? How do I start the activity "fresh"?
Thanks!
I suggest your read my answer to another mildly similar question. Basically, finish is exactly the same as the user hitting the back button. It's more-or-less up to you as the developer to change the state based on the interaction from the user (ie via the intent).
For example you could do something like the following...
Intent intent = new Intent();
Bundle bun = new Bundle();
bun.putBoolean("newGame", true);
intent.setClass(this, GameActivity.class);
intent.putExtras(bun);
startActivity(intent);
I guess you don't want to start the gamescreen when gameOver is true
public void button_clicked8(View v) {
if(gameOver) return;
startActivity(new Intent(this, GameScreen.class));
}
Use flag for intent when you start Activity.
How about reseting gameover
value in onCreate()
method of GameScreen?
Please read about activity lifecycles here and as far as setting your gameover
variable another way to store the value is with SharedPreferences
. Do it like this:
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("gameover", true);
editor.commit();
and to read your value, do it like this:
Boolean gameOver = sharedPreferences.getBoolean("gameover", true);
By doing this you are permanently setting your value and will not have to worry about activity lifecycle events.
u can declare a static boolean variable gameOver in levels.java.
which u can modify from end button click in GameScreen.java. when finish has been called all d variables r destroyed. u can override GameScreen.java's onCreate(),onResume(),onDestroy(),onStart(),onPause(),onStop() to handle ur variable
精彩评论