我是初學Java的Java程序員。我使用Eclipse創建了一個基本的Android遊戲,我想保存高分。我被告知要使用共享偏好,所以當我退出遊戲並再次打開遊戲時,會保存高分。我已經獲得了高分,可以保存在我的「主菜單」頁面上,但對共享首選項代碼的放置位置感到困惑?它應該在我的OnCreate中嗎?請看我的代碼,並嘗試幫助我。我知道它可能非常簡單,但我一直在這方面工作了一段時間。Java Android基本遊戲 - 使用共享偏好保存HighScore - TOTAL BEGINNER
下面的代碼:
package cct.mad.lab;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import cct.mad.lab.GameView;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.net.Uri;
public class MainMenu extends Activity {
//MediaPlayer backgroundmusic;////////////////////
private static final int SCORE_REQUEST_CODE = 1;// The request code for the intent
private static final int PREFERENCE_MODE_PRIVATE = 0;
TextView tvHighScore;
TextView tvLastScore;
//TextView tvScore
String score;
Intent gameIntent;
int HighNum = 0;
SoundPool sp;
MediaPlayer mp;
int hit = 0;
ImageView crash;
ImageView image;
//int highscore = 0;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.game_start);
tvHighScore = (TextView) findViewById(R.id.tvGuessGame);
tvLastScore = (TextView) findViewById(R.id.LastGameNumb);
}
public void startGame(View v)
{
gameIntent = new Intent(this,GameActivity.class);
startActivityForResult(gameIntent, SCORE_REQUEST_CODE);
mp = MediaPlayer.create(this, R.raw.bgmusic); // Assigns the media player to the bgmusic in the raw flder
mp.setLooping(true); // loops the media player so it continues to play
mp.start(); // starts the media player when the start game button is called
}
/* 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) {
mp.pause(); // Pauses the Mediaplayer when the game is stopped and returned to the main menu.
// 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");
if (scoreFromGame > HighNum)
{
tvHighScore.setText(Integer.toString(scoreFromGame));
tvLastScore.setText(Integer.toString(scoreFromGame));
HighNum = scoreFromGame;
}
else if (scoreFromGame > HighNum)
{
tvHighScore.setText(Integer.toString(scoreFromGame));
tvLastScore.setText(Integer.toString(scoreFromGame));
}
else if (scoreFromGame < HighNum)
{
tvLastScore.setText(Integer.toString(scoreFromGame));
}
}
}
}
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mp.stop(); // Stops the mediaplayer when the game/emulator is exited.
mp.release(); // Stops the mediaplayer when the game/emulator is exited.
}
/*
@Override
public void onSaveInstanceState(Bundle savedInstanceState){ // When activity stops, system calls onSaveInstancState to save info.
//Save the user's current game state
savedInstanceState.putInt("GAME_SCORE", HighNum);
super.onSaveInstanceState(savedInstanceState); //Calls superclass to view the hierachy state
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState){
super.onCreate(savedInstanceState); // Calls the superclass first
if (savedInstanceState != null) {
HighNum = savedInstanceState.getInt("GAME_SCORE");
} else {
}
super.onRestoreInstanceState(savedInstanceState);
}
*/
}
getSharedPreferences方法必須在onCreate()之後。我認爲onResume()是可以的。共享首選項只會保存密鑰對,直到應用程序被銷燬。您可以在onResume中獲得您的共享偏好設置,然後使用該功能創建編輯器。然後在高分創建時寫下並提交。在OnResume()中調用它們再次填充高分。但是如果應用程序被破壞,這又會丟失。也許使用SQLite? –
好,謝謝!無論如何,你可以給我一個例子,說明如何根據我的代碼設置和獲取共享首選項?如果我創建onPause來設置共享首選項。 SharedPreferences prefs = this.getSharedPreferences(「myPrefsKey」,Context.MODE_PRIVATE); Editor editor = prefs.edit(); editor.putInt(「key」,score); editor.commit();我會改變什麼來從我的比賽中得分?它目前存儲在上面代碼的tvhighscore文本視圖中。 – NewChaz
您將高分放在textView中,但實際得分在scoreFromGame中,如果大於HighNum則設置爲scoreFromGame。當你檢查HighNum時,你也應該設置首選項。把上面的所有代碼(在註釋中)放在一個函數中,並從if(scoreFromGame> HigNum)傳遞true部分並通過scoreFromGame調用它。然後使用editor.setInt(「hightScore」,scoreFromGame –