使用返回键返回 Android 应用上的主要 Activity 以查看用户得分
Going back to Main Activity on Android app with back key to see user score
希望我能得到一些建议。
我的程序有一个精灵,当 hit/clicked 时,屏幕上会显示分数。当游戏结束(时间用完)时,我希望用户能够按 phone 上的后退键返回到他们开始游戏的 main/start screen/activity , 但它也会显示他们的分数(点击次数)。
我正在努力弄清楚如何让它通过按返回键返回。如果需要的话,我可以在以后找出高分位。我只想回到那个开始屏幕。
更新:
我认为它为什么不起作用可能与我的清单有关。我试图将 'GameView' class 添加到清单中,但它不会接受。它说它没有默认构造函数。有什么想法吗?
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="cct.mad.lab.MainMenu"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".GameActivity"
android:label="@string/app_name" >
</activity>
<activity
android:name=".GameView"
android:label="@string/app_name" >
</activity>
我的 GameView 代码如下:
public class GameView extends SurfaceView implements SurfaceHolder.Callback {
/* Member (state) fields */
private GameLoopThread gameLoopThread;
private Paint paint; //Reference a paint object
/** The drawable to use as the background of the animation canvas */
private Bitmap mBackgroundImage;
// For creating the game Sprite
private Sprite sprite;
// For recording the number of hits
private int hitCount;
// To track if a game is over
private boolean gameOver;
// To play sound
private SoundPlayer sound;
//int backButtonCount = 0;
public GameView(Context context) {
super(context);
// Focus must be on GameView so that events can be handled.
this.setFocusable(true);
// For intercepting events on the surface.
this.getHolder().addCallback(this);
// Background image added
mBackgroundImage = BitmapFactory.decodeResource(this.getResources(), R.drawable.half_moon);
//sound = new SoundPlayer(this);
}
/* Called immediately after the surface created */
public void surfaceCreated(SurfaceHolder holder) {
// We can now safely setup the game start the game loop.
ResetGame();//Set up a new game up - could be called by a 'play again option'
mBackgroundImage = Bitmap.createScaledBitmap(mBackgroundImage, getWidth(), getHeight(), true);
gameLoopThread = new GameLoopThread(this.getHolder(), this);
gameLoopThread.running = true;
gameLoopThread.start();
}
// For the countdown timer
private long startTime; // Timer to count down from
private final long interval = 1 * 1000; // 1 sec interval
private CountDownTimer countDownTimer; // Reference to the class
private boolean timerRunning = false;
private String displayTime; // To display the time on the screen
//To initialise/reset game
private void ResetGame(){
/* Set paint details */
paint = new Paint();
paint.setColor(Color.WHITE);
paint.setTextSize(20);
sprite = new Sprite(this);
hitCount = 0;
// Set timer
startTime = 10; // Start at 10s to count down
// Create new object - convert startTime to milliseconds
countDownTimer = new MyCountDownTimer(startTime*1000, interval);
countDownTimer.start(); // Start the time running
timerRunning = true;
gameOver = false;
}
// Countdown Timer - private class
private class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer (long startTime, long interval) {
super(startTime, interval);
}
public void onFinish() {
//displayTime = "Time is up!";
timerRunning = false;
countDownTimer.cancel();
gameOver = true;
}
public void onTick (long millisUntilFinished) {
displayTime = " " + millisUntilFinished / 1000;
}
}
//This class updates and manages the assets prior to drawing - called from the Thread
public void update(){
sprite.update();
}
/**
* To draw the game to the screen
* This is called from Thread, so synchronisation can be done
*/
public void doDraw(Canvas canvas) {
//Draw all the objects on the canvas
canvas.drawBitmap(mBackgroundImage, 0, 0, null);
if (!gameOver) {
sprite.draw(canvas);
canvas.drawText("Time Remaining: " + displayTime, 35, 50, paint);
canvas.drawText("Number of hits: " + hitCount, 250, 50, paint);
} else
canvas.drawText("Game Over!", 185, 100, paint);
canvas.drawText("To go back to the main menu, press the 'back' key", 15, 150, paint);
}
//To be used if we need to find where screen was touched
public boolean onTouchEvent(MotionEvent event) {
if (sprite.wasItTouched(event.getX(), event.getY())) {
// This just renews the sprite for now
sprite = new Sprite(this);
//sound.playZapSound();
hitCount++;
}
return true;
}
public void surfaceDestroyed(SurfaceHolder holder) {
gameLoopThread.running = false;
// Shut down the game loop thread cleanly.
boolean retry = true;
while(retry) {
try {
gameLoopThread.join();
retry = false;
} catch (InterruptedException e) {}
}
}
public void getHitCount() {
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
}
我的 MainActivity 如下:
public class MainMenu extends Activity {
private static final int SCORE_REQUEST_CODE = 1;// The request code for the intent
TextView tvScore;
String score;
Intent gameIntent;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_start);
}
public void startGame(View v){
gameIntent = new Intent(this,GameActivity.class);
startActivityForResult(gameIntent, SCORE_REQUEST_CODE );
}
/* Create Options Menu */
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
// Respond to item selected on OPTIONS MENU
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
//put data in Intent
case R.id.easy:
Toast.makeText(this, "Easy chosen", Toast.LENGTH_SHORT).show();
return true;
case R.id.medium:
Toast.makeText(this, "Medium chosen", Toast.LENGTH_SHORT).show();
return true;
case R.id.hard:
Toast.makeText(this, "Hard chosen", Toast.LENGTH_SHORT).show();
return true;
case R.id.other:
Toast.makeText(this, "Other chosen", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent retIntent) {
// Check which request we're responding to
if (requestCode == SCORE_REQUEST_CODE) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
if (retIntent.hasExtra("GAME_SCORE")) {
int scoreFromGame = retIntent.getExtras().getInt("GAME_SCORE");
tvScore.setText(Integer.toString(scoreFromGame));
}
}
}
}
}
一如既往,非常感谢您的帮助。
谢谢
使用 onBackPressed。
@Override
public void onBackPressed() {
Intent i= new Intent(your_present_activity.this,the_activity_you_want_to_jump_to.class);
startActivity(i);
finish();
}
您可以使用 newintent.putExtra(name,"key");
将您的分数提高到 Main.class
我的后退按钮不起作用的问题似乎完全归因于我在 doDraw 方法中的 else 语句,这两个语句没有用大括号括起来。添加了那些,它工作正常。按下后退按钮时会自动调用 surfaceDestroyed 方法,因为这会停止 gameLoopThread class.
感谢所有试图帮助我的人。
希望我能得到一些建议。
我的程序有一个精灵,当 hit/clicked 时,屏幕上会显示分数。当游戏结束(时间用完)时,我希望用户能够按 phone 上的后退键返回到他们开始游戏的 main/start screen/activity , 但它也会显示他们的分数(点击次数)。
我正在努力弄清楚如何让它通过按返回键返回。如果需要的话,我可以在以后找出高分位。我只想回到那个开始屏幕。
更新:
我认为它为什么不起作用可能与我的清单有关。我试图将 'GameView' class 添加到清单中,但它不会接受。它说它没有默认构造函数。有什么想法吗?
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="cct.mad.lab.MainMenu"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".GameActivity"
android:label="@string/app_name" >
</activity>
<activity
android:name=".GameView"
android:label="@string/app_name" >
</activity>
我的 GameView 代码如下:
public class GameView extends SurfaceView implements SurfaceHolder.Callback {
/* Member (state) fields */
private GameLoopThread gameLoopThread;
private Paint paint; //Reference a paint object
/** The drawable to use as the background of the animation canvas */
private Bitmap mBackgroundImage;
// For creating the game Sprite
private Sprite sprite;
// For recording the number of hits
private int hitCount;
// To track if a game is over
private boolean gameOver;
// To play sound
private SoundPlayer sound;
//int backButtonCount = 0;
public GameView(Context context) {
super(context);
// Focus must be on GameView so that events can be handled.
this.setFocusable(true);
// For intercepting events on the surface.
this.getHolder().addCallback(this);
// Background image added
mBackgroundImage = BitmapFactory.decodeResource(this.getResources(), R.drawable.half_moon);
//sound = new SoundPlayer(this);
}
/* Called immediately after the surface created */
public void surfaceCreated(SurfaceHolder holder) {
// We can now safely setup the game start the game loop.
ResetGame();//Set up a new game up - could be called by a 'play again option'
mBackgroundImage = Bitmap.createScaledBitmap(mBackgroundImage, getWidth(), getHeight(), true);
gameLoopThread = new GameLoopThread(this.getHolder(), this);
gameLoopThread.running = true;
gameLoopThread.start();
}
// For the countdown timer
private long startTime; // Timer to count down from
private final long interval = 1 * 1000; // 1 sec interval
private CountDownTimer countDownTimer; // Reference to the class
private boolean timerRunning = false;
private String displayTime; // To display the time on the screen
//To initialise/reset game
private void ResetGame(){
/* Set paint details */
paint = new Paint();
paint.setColor(Color.WHITE);
paint.setTextSize(20);
sprite = new Sprite(this);
hitCount = 0;
// Set timer
startTime = 10; // Start at 10s to count down
// Create new object - convert startTime to milliseconds
countDownTimer = new MyCountDownTimer(startTime*1000, interval);
countDownTimer.start(); // Start the time running
timerRunning = true;
gameOver = false;
}
// Countdown Timer - private class
private class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer (long startTime, long interval) {
super(startTime, interval);
}
public void onFinish() {
//displayTime = "Time is up!";
timerRunning = false;
countDownTimer.cancel();
gameOver = true;
}
public void onTick (long millisUntilFinished) {
displayTime = " " + millisUntilFinished / 1000;
}
}
//This class updates and manages the assets prior to drawing - called from the Thread
public void update(){
sprite.update();
}
/**
* To draw the game to the screen
* This is called from Thread, so synchronisation can be done
*/
public void doDraw(Canvas canvas) {
//Draw all the objects on the canvas
canvas.drawBitmap(mBackgroundImage, 0, 0, null);
if (!gameOver) {
sprite.draw(canvas);
canvas.drawText("Time Remaining: " + displayTime, 35, 50, paint);
canvas.drawText("Number of hits: " + hitCount, 250, 50, paint);
} else
canvas.drawText("Game Over!", 185, 100, paint);
canvas.drawText("To go back to the main menu, press the 'back' key", 15, 150, paint);
}
//To be used if we need to find where screen was touched
public boolean onTouchEvent(MotionEvent event) {
if (sprite.wasItTouched(event.getX(), event.getY())) {
// This just renews the sprite for now
sprite = new Sprite(this);
//sound.playZapSound();
hitCount++;
}
return true;
}
public void surfaceDestroyed(SurfaceHolder holder) {
gameLoopThread.running = false;
// Shut down the game loop thread cleanly.
boolean retry = true;
while(retry) {
try {
gameLoopThread.join();
retry = false;
} catch (InterruptedException e) {}
}
}
public void getHitCount() {
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
}
我的 MainActivity 如下:
public class MainMenu extends Activity {
private static final int SCORE_REQUEST_CODE = 1;// The request code for the intent
TextView tvScore;
String score;
Intent gameIntent;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_start);
}
public void startGame(View v){
gameIntent = new Intent(this,GameActivity.class);
startActivityForResult(gameIntent, SCORE_REQUEST_CODE );
}
/* Create Options Menu */
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
// Respond to item selected on OPTIONS MENU
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
//put data in Intent
case R.id.easy:
Toast.makeText(this, "Easy chosen", Toast.LENGTH_SHORT).show();
return true;
case R.id.medium:
Toast.makeText(this, "Medium chosen", Toast.LENGTH_SHORT).show();
return true;
case R.id.hard:
Toast.makeText(this, "Hard chosen", Toast.LENGTH_SHORT).show();
return true;
case R.id.other:
Toast.makeText(this, "Other chosen", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent retIntent) {
// Check which request we're responding to
if (requestCode == SCORE_REQUEST_CODE) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
if (retIntent.hasExtra("GAME_SCORE")) {
int scoreFromGame = retIntent.getExtras().getInt("GAME_SCORE");
tvScore.setText(Integer.toString(scoreFromGame));
}
}
}
}
}
一如既往,非常感谢您的帮助。
谢谢
使用 onBackPressed。
@Override
public void onBackPressed() {
Intent i= new Intent(your_present_activity.this,the_activity_you_want_to_jump_to.class);
startActivity(i);
finish();
}
您可以使用 newintent.putExtra(name,"key");
将您的分数提高到 Main.class我的后退按钮不起作用的问题似乎完全归因于我在 doDraw 方法中的 else 语句,这两个语句没有用大括号括起来。添加了那些,它工作正常。按下后退按钮时会自动调用 surfaceDestroyed 方法,因为这会停止 gameLoopThread class.
感谢所有试图帮助我的人。